diff --git a/Src/Asp.NetCore2/DB2CoreTest/CURD/CodeFirst.cs b/Src/Asp.NetCore2/DB2CoreTest/CURD/CodeFirst.cs new file mode 100644 index 000000000..fc1502553 --- /dev/null +++ b/Src/Asp.NetCore2/DB2CoreTest/CURD/CodeFirst.cs @@ -0,0 +1,220 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DB2CoreTest.CURD +{ + public class CodeFirst + { + public static void Init() + { + // 获取新的数据库实例 + var db = DbHelper.GetNewDb(); + + // 如果数据库不存在,则创建数据库 + //db.DbMaintenance.CreateDatabase(); + + //实体类初始化表 + db.CodeFirst.InitTables(); + + //实体类初始化表 + db.CodeFirst.InitTables(); + } + + public static void Insertable() + { + // 获取新的数据库实例 + var db = DbHelper.GetNewDb(); + + //插入用户 + var userId = db.Insertable(new UserInfo() + { + Context = "Context", + Email = "dfafa@qq.com", + Price = Convert.ToDecimal(1.1), + UserName = "admin", + RegistrationDate = DateTime.Now, + + }).ExecuteReturnIdentity(); + + //插入用户登录 + var loginId = db.Insertable(new UserLogins() + { + LoginTime = DateTime.Now, + UserId = userId, + + }).ExecuteReturnIdentity(); + } + + public static void Queryable() + { + // 获取新的数据库实例 + var db = DbHelper.GetNewDb(); + + //查询用户 + var userInfo = db.Queryable().ToList(); + + //查询用户登录 + var userLogin = db.Queryable().ToList(); + } + + public static void JoinQuery() + { + // 获取新的数据库实例 + var db = DbHelper.GetNewDb(); + + var queryResult = db.Queryable((ui, ul) => new JoinQueryInfos(JoinType.Inner, ui.UserId == ul.UserId)).Select((ui, ul) => new + { + ui.UserName, + ul.LoginTime, + }).ToList(); + } + + public static void PageQuery() + { + // 获取新的数据库实例 + var db = DbHelper.GetNewDb(); + + //查询用户 + var userList = db.Queryable().ToPageList(2, 2); + + var queryResult = db.Queryable((ui, ul) => new JoinQueryInfos(JoinType.Inner, ui.UserId == ul.UserId)).Select((ui, ul) => new + { + ui.UserName, + ul.LoginTime, + }).ToPageList(2, 2); + } + + public static void OrderBy() + { + // 获取新的数据库实例 + var db = DbHelper.GetNewDb(); + + //查询用户 + var userList = db.Queryable().OrderBy(p => p.UserName).ToList(); + + var queryResult = db.Queryable((ui, ul) => new JoinQueryInfos(JoinType.Inner, ui.UserId == ul.UserId)).Select((ui, ul) => new + { + ui.UserName, + ul.LoginTime, + }).OrderBy(ui => ui.UserName).ToList(); + } + + public static void GroupBy() + { + // 获取新的数据库实例 + var db = DbHelper.GetNewDb(); + + //查询用户 + var userList = db.Queryable().GroupBy(p => p.Email).Select(p => new { UserId = SqlFunc.AggregateMax(p.UserId), p.Email, }).OrderBy(p => p.UserId).ToList(); + + var queryResult = db.Queryable((ui, ul) => new JoinQueryInfos(JoinType.Inner, ui.UserId == ul.UserId)).GroupBy((ui, ul) => + new + { + ui.UserName, + }) + .Select((ui, ul) => new + { + UserId = SqlFunc.AggregateMax(ui.UserId), + ui.UserName, + LoginTime = SqlFunc.AggregateMax(ul.LoginTime), + }).OrderBy(ui => ui.UserName).ToList(); + } + + public static void Updateable() + { + // 获取新的数据库实例 + var db = DbHelper.GetNewDb(); + + //更新用户 + var ret = db.Updateable(p => p.UserName == "test").Where(p => p.UserName == "admin").ExecuteCommand(); + } + + public static void Deleteable() + { + // 获取新的数据库实例 + var db = DbHelper.GetNewDb(); + + //查询用户 + var userList = db.Queryable().ToList(); + //删除用户 + var deleteUserRet = db.Deleteable(userList).ExecuteCommand(); + + //查询用户登录 + var userLoginList = db.Queryable().ToList(); + //删除用户登录 + var deleteUserLoginRet = db.Deleteable(userLoginList).ExecuteCommand(); + } + } + + /// + /// 用户信息实体类 + /// + [SugarTable("USER_INFO", TableDescription = "用户信息")] + public class UserInfo + { + /// + /// 用户ID(主键) + /// + [SugarColumn(IsIdentity = true, IsPrimaryKey = true, ColumnDescription = "用户ID")] + public int UserId { get; set; } + + /// + /// 用户名 + /// + [SugarColumn(Length = 50, IsNullable = false, ColumnDescription = "用户名")] + public string UserName { get; set; } + + /// + /// 用户邮箱 + /// + [SugarColumn(IsNullable = true, ColumnDescription = "用户邮箱")] + public string Email { get; set; } + + /// + /// 产品价格 + /// + [SugarColumn(ColumnDescription = "产品价格")] + public decimal Price { get; set; } + + /// + /// 用户内容 + /// + [SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString, IsNullable = true, ColumnDescription = "用户内容")] + public string Context { get; set; } + + /// + /// 用户注册日期 + /// + [SugarColumn(IsNullable = true, ColumnDescription = "用户注册日期")] + public DateTime? RegistrationDate { get; set; } + } + + /// + /// 用户登录实体类 + /// + [SugarTable("USER_LOGINS")] + public class UserLogins + { + /// + /// ID(主键) + /// + [SugarColumn(IsIdentity = true, IsPrimaryKey = true)] + public int Id { get; set; } + + /// + /// 用户ID + /// + [SugarColumn(IsNullable = false)] + public int UserId { get; set; } + + /// + /// 登录时间 + /// + [SugarColumn(IsNullable = true)] + public DateTime LoginTime { get; set; } + } +} diff --git a/Src/Asp.NetCore2/DB2CoreTest/DB2CoreTest.csproj b/Src/Asp.NetCore2/DB2CoreTest/DB2CoreTest.csproj new file mode 100644 index 000000000..5c27613be --- /dev/null +++ b/Src/Asp.NetCore2/DB2CoreTest/DB2CoreTest.csproj @@ -0,0 +1,23 @@ + + + + Exe + net8.0 + enable + enable + AnyCPU + + + + full + + + + full + + + + + + + diff --git a/Src/Asp.NetCore2/DB2CoreTest/Program.cs b/Src/Asp.NetCore2/DB2CoreTest/Program.cs new file mode 100644 index 000000000..ea4856e72 --- /dev/null +++ b/Src/Asp.NetCore2/DB2CoreTest/Program.cs @@ -0,0 +1,62 @@ +using DB2CoreTest.CURD; +using SqlSugar; + +public class Program +{ + static void Main(string[] args) + { + //CodeFirst.Init(); + CodeFirst.Insertable(); + CodeFirst.Queryable(); + CodeFirst.JoinQuery(); + CodeFirst.PageQuery(); + CodeFirst.OrderBy(); + CodeFirst.GroupBy(); + CodeFirst.Updateable(); + CodeFirst.Deleteable(); + } +} + +/// +/// Helper class for database operations +/// 数据库操作的辅助类 +/// +public class DbHelper +{ + /// + /// Database connection string + /// 数据库连接字符串 + /// + public readonly static string Connection = "server=127.0.0.1:50000;database=Test;uid=db2inst1;pwd=123456;"; + + /// + /// Get a new SqlSugarClient instance with specific configurations + /// 获取具有特定配置的新 SqlSugarClient 实例 + /// + /// SqlSugarClient instance + public static SqlSugarClient GetNewDb() + { + InstanceFactory.CustomDbName = "DB2";//文件名前缀 + InstanceFactory.CustomDllName = "SqlSugar.DB2Core";//你扩展的dll名字 + InstanceFactory.CustomNamespace = "SqlSugar.DB2";//你扩展dll的命名空间 + + var db = new SqlSugarClient(new ConnectionConfig() + { + IsAutoCloseConnection = true, + DbType = DbType.Custom, + ConnectionString = Connection, + InitKeyType = InitKeyType.Attribute, + LanguageType = LanguageType.Default//Set language + }, + it => + { + // Logging SQL statements and parameters before execution + // 在执行前记录 SQL 语句和参数 + it.Aop.OnLogExecuting = (sql, para) => + { + Console.WriteLine(UtilMethods.GetNativeSql(sql, para)); + }; + }); + return db; + } +} \ No newline at end of file diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/CodeFirst/Db2CodeFirst.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/CodeFirst/Db2CodeFirst.cs new file mode 100644 index 000000000..e9831f16b --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/CodeFirst/Db2CodeFirst.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar.DB2 +{ + public class DB2CodeFirst : CodeFirstProvider + { + protected override void ExistLogicEnd(List dbColumns) + { + foreach (EntityColumnInfo column in dbColumns) + { + if (column.DefaultValue != null) + { + this.Context.DbMaintenance.AddDefaultValue(column.DbTableName,column.DbColumnName,column.DefaultValue.ToSqlValue()); + } + } + } + public override void NoExistLogic(EntityInfo entityInfo) + { + var tableName = GetTableName(entityInfo); + //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); + List columns = new List(); + if (entityInfo.Columns.HasValue()) + { + foreach (var item in entityInfo.Columns.Where(it=>it.IsIgnore==false)) + { + DbColumnInfo dbColumnInfo = this.EntityColumnToDbColumn(entityInfo, tableName, item); + columns.Add(dbColumnInfo); + } + if (entityInfo.IsCreateTableFiledSort) + { + columns = columns.OrderBy(c => c.CreateTableFieldSort).ToList(); + } + } + columns = columns.OrderBy(it => it.IsPrimarykey ? 0 : 1).ToList(); + this.Context.DbMaintenance.CreateTable(tableName, columns,true); + } + protected override DbColumnInfo EntityColumnToDbColumn(EntityInfo entityInfo, string tableName, EntityColumnInfo item) + { + var propertyType = UtilMethods.GetUnderType(item.PropertyInfo); + var result = new DbColumnInfo() + { + TableId = entityInfo.Columns.IndexOf(item), + DbColumnName = item.DbColumnName.HasValue() ? item.DbColumnName : item.PropertyName, + IsPrimarykey = item.IsPrimarykey, + IsIdentity = item.IsIdentity, + TableName = tableName, + IsNullable = item.IsNullable, + DefaultValue = item.DefaultValue, + ColumnDescription = item.ColumnDescription, + Length = item.Length, + CreateTableFieldSort = item.CreateTableFieldSort + }; + if (propertyType == UtilConstants.DecType) + { + result.Scale = item.DecimalDigits; + result.DecimalDigits = item.DecimalDigits; + } + GetDbType(item, propertyType, result); + if (result.DataType.Equals("varchar", StringComparison.CurrentCultureIgnoreCase) && result.Length == 0) + { + result.Length = 1; + } + return result; + } + + protected override void ConvertColumns(List dbColumns) + { + foreach (var item in dbColumns) + { + if (item.DataType == "DateTime") + { + item.Length = 0; + } + } + } + + protected override void ChangeKey(EntityInfo entityInfo, string tableName, EntityColumnInfo item) + { + this.Context.DbMaintenance.UpdateColumn(tableName, EntityColumnToDbColumn(entityInfo, tableName, item)); + if (!item.IsPrimarykey) + this.Context.DbMaintenance.DropConstraint(tableName,null); + if (item.IsPrimarykey) + this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName); + } + + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DB2Provider.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DB2Provider.cs new file mode 100644 index 000000000..2fa58b05d --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DB2Provider.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using IBM.Data.Db2; + +namespace SqlSugar.DB2 +{ + public partial class DB2Provider : AdoProvider + { + public DB2Provider() + { + + } + + public override IDbConnection Connection + { + get + { + if (base._DbConnection == null) + { + try + { + var connectionString = base.Context.CurrentConnectionConfig.ConnectionString; + + var connection = new DB2Connection(connectionString); + base._DbConnection = connection; + } + catch (Exception ex) + { + throw ex; + + } + } + return base._DbConnection; + } + set + { + base._DbConnection = value; + } + } + + public override void BeginTran(string transactionName) + { + base.BeginTran(); + } + /// + /// Only SqlServer + /// + /// + /// + public override void BeginTran(IsolationLevel iso, string transactionName) + { + base.BeginTran(iso); + } + public override IDataAdapter GetAdapter() + { + return new DB2DataAdapter(); + } + public override DbCommand GetCommand(string sql, SugarParameter[] parameters) + { + DB2Command sqlCommand = new DB2Command(sql, (DB2Connection)this.Connection); + sqlCommand.CommandType = this.CommandType; + sqlCommand.CommandTimeout = this.CommandTimeOut; + if (this.Transaction != null) + { + sqlCommand.Transaction = (DB2Transaction)this.Transaction; + } + if (parameters.HasValue()) + { + IDataParameter[] ipars = ToIDbDataParameter(parameters); + sqlCommand.Parameters.AddRange((DB2Parameter[])ipars); + } + CheckConnection(); + return sqlCommand; + } + public override void SetCommandToAdapter(IDataAdapter dataAdapter, DbCommand command) + { + ((DB2DataAdapter)dataAdapter).SelectCommand = (DB2Command)command; + } + /// + /// if mysql return MySqlParameter[] pars + /// if sqlerver return SqlParameter[] pars ... + /// + /// + /// + public override IDataParameter[] ToIDbDataParameter(params SugarParameter[] parameters) + { + if (parameters == null || parameters.Length == 0) return null; + DB2Parameter[] result = new DB2Parameter[parameters.Length]; + int index = 0; + var isVarchar = this.Context.IsVarchar(); + foreach (var parameter in parameters) + { + if (parameter.Value == null) parameter.Value = DBNull.Value; + if (parameter.Value is System.Data.SqlTypes.SqlDateTime && parameter.DbType == System.Data.DbType.AnsiString) + { + parameter.DbType = System.Data.DbType.DateTime; + parameter.Value = DBNull.Value; + } + UNumber(parameter); + var sqlParameter = new DB2Parameter(); + sqlParameter.ParameterName = parameter.ParameterName; + sqlParameter.Size = parameter.Size; + sqlParameter.Value = parameter.Value; + sqlParameter.DbType = parameter.DbType; + sqlParameter.Direction = ParameterDirection.InputOutput; + if (parameter.IsJson) + { + sqlParameter.DB2Type = DB2Type.DbClob; + } + if (parameter.IsArray) + { + Array(parameter, sqlParameter); + } + if (sqlParameter.Direction == 0) + { + sqlParameter.Direction = ParameterDirection.Input; + } + result[index] = sqlParameter; + if (sqlParameter.Direction.IsIn(ParameterDirection.Output, ParameterDirection.InputOutput, ParameterDirection.ReturnValue)) + { + if (this.OutputParameters == null) this.OutputParameters = new List(); + this.OutputParameters.RemoveAll(it => it.ParameterName == sqlParameter.ParameterName); + this.OutputParameters.Add(sqlParameter); + } + if (isVarchar && sqlParameter.DbType == System.Data.DbType.String) + { + sqlParameter.DbType = System.Data.DbType.AnsiString; + } + else if (sqlParameter.Value is DateTime && sqlParameter.DbType == System.Data.DbType.AnsiString) + { + sqlParameter.DbType = System.Data.DbType.DateTime; + } + ++index; + if (parameter.CustomDbType != null && parameter.CustomDbType is DB2Type) + { + sqlParameter.DB2Type = ((DB2Type)parameter.CustomDbType); + } + } + return result; + } + + private static void Array(SugarParameter parameter, DB2Parameter sqlParameter) + { + // sqlParameter.Value = this.Context.Utilities.SerializeObject(sqlParameter.Value); + var type = sqlParameter.Value.GetType(); + if (ArrayMapping.ContainsKey(type)) + { + sqlParameter.DB2Type = ArrayMapping[type] | DB2Type.DynArray; + } + else if (type == DBNull.Value.GetType()) + { + DbNullParametrerArray(parameter, sqlParameter); + + } + else + { + Check.Exception(true, sqlParameter.Value.GetType().Name + " No Support"); + } + } + + private static void DbNullParametrerArray(SugarParameter parameter, DB2Parameter sqlParameter) + { + if (parameter.DbType.IsIn(System.Data.DbType.Int32)) + { + sqlParameter.DB2Type = DB2Type.Integer | DB2Type.DynArray; + } + else if (parameter.DbType.IsIn(System.Data.DbType.Int16)) + { + sqlParameter.DB2Type = DB2Type.SmallInt | DB2Type.DynArray; + } + else if (parameter.DbType.IsIn(System.Data.DbType.Int64)) + { + sqlParameter.DB2Type = DB2Type.BigInt | DB2Type.DynArray; + } + else if (parameter.DbType.IsIn(System.Data.DbType.Guid)) + { + sqlParameter.DB2Type = DB2Type.VarChar | DB2Type.DynArray; + } + else + { + sqlParameter.DB2Type = DB2Type.Text | DB2Type.DynArray; + } + } + + private static void UNumber(SugarParameter parameter) + { + if (parameter.DbType == System.Data.DbType.UInt16) + { + parameter.DbType = System.Data.DbType.Int16; + parameter.Value = Convert.ToInt16(parameter.Value); + } + else if (parameter.DbType == System.Data.DbType.UInt32) + { + parameter.DbType = System.Data.DbType.Int32; + parameter.Value = Convert.ToInt32(parameter.Value); + } + else if (parameter.DbType == System.Data.DbType.UInt64) + { + parameter.DbType = System.Data.DbType.Int64; + parameter.Value = Convert.ToInt64(parameter.Value); + } + } + + static readonly Dictionary ArrayMapping = new Dictionary() + { + { typeof(int[]),DB2Type.Integer}, + { typeof(short[]),DB2Type.SmallInt}, + { typeof(long[]),DB2Type.BigInt}, + { typeof(decimal[]),DB2Type.Numeric}, + { typeof(char[]),DB2Type.Clob}, + { typeof(byte[]),DB2Type.Byte}, + { typeof(bool[]),DB2Type.Boolean}, + {typeof(DateTime[]),DB2Type.Date}, + {typeof(float[]),DB2Type.Real}, + {typeof(Guid[]),DB2Type.VarChar}, + + + { typeof(int?[]),DB2Type.Integer}, + { typeof(short?[]),DB2Type.SmallInt}, + { typeof(long?[]),DB2Type.BigInt}, + { typeof(decimal?[]),DB2Type.Numeric}, + { typeof(char?[]),DB2Type.Text}, + { typeof(byte?[]),DB2Type.Byte}, + { typeof(bool?[]),DB2Type.Boolean}, + {typeof(DateTime?[]),DB2Type.Date}, + {typeof(Guid?[]),DB2Type.VarChar}, + + + { typeof(string[]), DB2Type.Text}, + {typeof(float?[]),DB2Type.Real}, + }; + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DbBind/DB2DbBind.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DbBind/DB2DbBind.cs new file mode 100644 index 000000000..81f3a3eb0 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DbBind/DB2DbBind.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SqlSugar.DB2 +{ + public class DB2DbBind : DbBindProvider + { + public override string GetDbTypeName(string csharpTypeName) + { + if (csharpTypeName == UtilConstants.ByteArrayType.Name) + return "bytea"; + if (csharpTypeName.ToLower() == "int32") + csharpTypeName = "int"; + if (csharpTypeName.ToLower() == "int16") + csharpTypeName = "short"; + if (csharpTypeName.ToLower() == "int64") + csharpTypeName = "long"; + if (csharpTypeName.ToLower().IsIn("boolean", "bool")) + csharpTypeName = "bool"; + if (csharpTypeName == "DateTimeOffset") + csharpTypeName = "DateTime"; + var mappings = this.MappingTypes.Where(it => it.Value.ToString().Equals(csharpTypeName, StringComparison.CurrentCultureIgnoreCase)).ToList(); + if (mappings != null && mappings.Count > 0) + return mappings.First().Key; + else + return "varchar"; + } + public override string GetPropertyTypeName(string dbTypeName) + { + dbTypeName = dbTypeName.ToLower(); + var propertyTypes = MappingTypes.Where(it => it.Value.ToString().ToLower() == dbTypeName || it.Key.ToLower() == dbTypeName); + if (propertyTypes == null) + { + return "other"; + } + else if (dbTypeName == "xml" || dbTypeName == "string" || dbTypeName == "jsonb" || dbTypeName == "json") + { + return "string"; + } + else if (dbTypeName == "bpchar")//数据库char datatype 查询出来的时候是 bpchar + { + return "char"; + } + if (dbTypeName == "byte[]") + { + return "byte[]"; + } + else if (propertyTypes == null || propertyTypes.Count() == 0) + { + if (dbTypeName.StartsWith("_")) + { + var dbTypeName2 = dbTypeName.TrimStart('_'); + return MappingTypes.Where(it => it.Value.ToString().ToLower() == dbTypeName2 || it.Key.ToLower() == dbTypeName2).Select(it => it.Value + "[]").First(); + } + Check.ThrowNotSupportedException(string.Format(" \"{0}\" Type NotSupported, DbBindProvider.GetPropertyTypeName error.", dbTypeName)); + return null; + } + else if (propertyTypes.First().Value == CSharpDataType.byteArray) + { + return "byte[]"; + } + else + { + return propertyTypes.First().Value.ToString(); + } + } + public override List> MappingTypes + { + get + { + var extService = this.Context.CurrentConnectionConfig.ConfigureExternalServices; + if (extService != null && extService.AppendDataReaderTypeMappings.HasValue()) + { + return extService.AppendDataReaderTypeMappings.Union(MappingTypesConst).ToList(); + } + else + { + return MappingTypesConst; + } + } + } + public static List> MappingTypesConst = new List>(){ + + new KeyValuePair("varbinary",CSharpDataType.@byteArray), + new KeyValuePair("binary",CSharpDataType.@byteArray), + new KeyValuePair("blob",CSharpDataType.@byteArray), + + new KeyValuePair("varchar",CSharpDataType.@string), + new KeyValuePair("char",CSharpDataType.@string), + new KeyValuePair("clob",CSharpDataType.@string), + + new KeyValuePair("date",CSharpDataType.@DateTime), + new KeyValuePair("time",CSharpDataType.@DateTime), + new KeyValuePair("timestamp",CSharpDataType.@DateTime), + + new KeyValuePair("integer",CSharpDataType.@int), + new KeyValuePair("smallint",CSharpDataType.@short), + new KeyValuePair("smallint",CSharpDataType.@byte), + new KeyValuePair("bigint",CSharpDataType.@long), + + new KeyValuePair("real",CSharpDataType.Single), + new KeyValuePair("float",CSharpDataType.@float), + new KeyValuePair("double",CSharpDataType.@double), + new KeyValuePair("decimal",CSharpDataType.@decimal), + new KeyValuePair("numeric",CSharpDataType.@decimal), + + }; + public override List StringThrow + { + get + { + return new List() { "int32", "datetime", "decimal", "double", "byte" }; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DbFirst/DB2DbFirst.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DbFirst/DB2DbFirst.cs new file mode 100644 index 000000000..d89703a55 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DbFirst/DB2DbFirst.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar.DB2 +{ + public class DB2DbFirst : DbFirstProvider + { + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DbMaintenance/DB2DbMaintenance.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DbMaintenance/DB2DbMaintenance.cs new file mode 100644 index 000000000..9177010cd --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/DbMaintenance/DB2DbMaintenance.cs @@ -0,0 +1,454 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar.DB2 +{ + public class DB2DbMaintenance : DbMaintenanceProvider + { + #region DML + protected override string GetDataBaseSql + { + get + { + return "SELECT SCHEMANAME FROM SYSCAT.schemata"; + } + } + protected override string GetColumnInfosByTableNameSql + { + get + { + string schema = GetSchema(); + string sql = @$"SELECT + tbl.TABLEID AS TableId, + tbl.TABNAME AS TableName, + col.COLNAME AS DbColumnName, + col.TYPENAME AS DataType, + col.""LENGTH"" AS LENGTH, + col.""DEFAULT"" AS DefaultValue, + col.""SCALE"" AS DecimalDigits, + col.""SCALE"" AS Scale, + col.REMARKS AS ColumnDescription, + CASE WHEN NVL(col.KEYSEQ,0)>0 THEN 1 ELSE 0 END AS IsPrimaryKey, + CASE WHEN col.""IDENTITY""='Y' THEN 1 ELSE 0 END AS IsIdentity, + CASE WHEN col.""NULLS"" ='Y' THEN 1 ELSE 0 END AS IsNullable + from syscat.tables tbl,SYSCAT.COLUMNS col WHERE tbl.TABSCHEMA = col.TABSCHEMA AND tbl.TABNAME =col.TABNAME + AND tbl.TABSCHEMA ='{schema}' AND tbl.TABNAME = '{{0}}' + ORDER BY tbl.TABSCHEMA,tbl.TABNAME,col.COLNO"; + return sql; + } + } + + protected override string GetTableInfoListSql + { + get + { + var schema = GetSchema(); + return @$"SELECT TABNAME AS Name,REMARKS AS Description, CASE TYPE WHEN 'T' THEN 0 WHEN 'V' THEN 1 END AS DbObjectType + FROM SYSCAT.tables WHERE TABSCHEMA ='{schema}' AND TYPE IN('T','V')"; + } + } + protected override string GetViewInfoListSql + { + get + { + return @"select cast(relname as varchar) as Name,cast(Description as varchar) from pg_description + join pg_class on pg_description.objoid = pg_class.oid + where objsubid = 0 and relname in (SELECT viewname from pg_views + WHERE schemaname ='" + GetSchema() + "')"; + } + } + #endregion + + #region DDL + protected override string CreateDataBaseSql + { + get + { + return "CREATE DATABASE {0}"; + } + } + protected override string AddPrimaryKeySql + { + get + { + return "ALTER TABLE {0} ADD PRIMARY KEY({2}) /*{1}*/"; + } + } + protected override string AddColumnToTableSql + { + get + { + return "ALTER TABLE {0} ADD COLUMN {1} {2}{3} {4} {5} {6}"; + } + } + protected override string AlterColumnToTableSql + { + get + { + return "alter table {0} ALTER COLUMN {1} {2}{3} {4} {5} {6}"; + } + } + protected override string BackupDataBaseSql + { + get + { + return "mysqldump.exe {0} -uroot -p > {1} "; + } + } + protected override string CreateTableSql + { + get + { + return "CREATE TABLE {0}(\r\n{1})"; + } + } + protected override string CreateTableColumn + { + get + { + return "{0} {1}{2} {3} {4} {5}"; + } + } + protected override string TruncateTableSql + { + get + { + return "TRUNCATE TABLE {0}"; + } + } + protected override string BackupTableSql + { + get + { + return "create table {0} as (select * from {1} limit {2} offset 0)"; + } + } + protected override string DropTableSql + { + get + { + return "DROP TABLE {0}"; + } + } + protected override string DropColumnToTableSql + { + get + { + return "ALTER TABLE {0} DROP COLUMN {1}"; + } + } + protected override string DropConstraintSql + { + get + { + return "ALTER TABLE {0} DROP CONSTRAINT {1}"; + } + } + protected override string RenameColumnSql + { + get + { + return "ALTER TABLE {0} RENAME {1} TO {2}"; + } + } + protected override string AddColumnRemarkSql => "comment on column {1}.{0} is '{2}'"; + + protected override string DeleteColumnRemarkSql => "comment on column {1}.{0} is ''"; + + protected override string IsAnyColumnRemarkSql { get { throw new NotSupportedException(); } } + + protected override string AddTableRemarkSql => "comment on table {0} is '{1}'"; + + protected override string DeleteTableRemarkSql => "comment on table {0} is ''"; + + protected override string IsAnyTableRemarkSql { get { throw new NotSupportedException(); } } + + protected override string RenameTableSql => "alter table {0} to {1}"; + + protected override string CreateIndexSql + { + get + { + return "CREATE {3} INDEX Index_{0}_{2} ON {0} ({1})"; + } + } + protected override string AddDefaultValueSql + { + get + { + return "ALTER TABLE {0} ALTER COLUMN {1} SET DEFAULT {2}"; + } + } + protected override string IsAnyIndexSql + { + get + { + return " SELECT count(1) WHERE upper('{0}') IN ( SELECT upper(indexname) FROM pg_indexes )"; + } + } + protected override string IsAnyProcedureSql => throw new NotImplementedException(); + #endregion + + #region Check + protected override string CheckSystemTablePermissionsSql + { + get + { + return "select * from syscat.tables"; + } + } + #endregion + + #region Scattered + protected override string CreateTableNull + { + get + { + return "DEFAULT NULL"; + } + } + protected override string CreateTableNotNull + { + get + { + return "NOT NULL"; + } + } + protected override string CreateTablePirmaryKey + { + get + { + return "PRIMARY KEY"; + } + } + protected override string CreateTableIdentity + { + get + { + return "GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1 )"; + } + } + #endregion + + #region Methods + public override List GetIndexList(string tableName) + { + var sql = $"SELECT indexname, indexdef FROM pg_indexes WHERE upper(tablename) = upper('{tableName}')"; + return this.Context.Ado.SqlQuery(sql); + } + public override List GetProcList(string dbName) + { + var sql = $"SELECT proname FROM pg_proc p JOIN pg_namespace n ON p.pronamespace = n.oid WHERE n.nspname = '{dbName}'"; + return this.Context.Ado.SqlQuery(sql); + } + public override bool AddDefaultValue(string tableName, string columnName, string defaultValue) + { + return base.AddDefaultValue(this.SqlBuilder.GetTranslationTableName(tableName), this.SqlBuilder.GetTranslationTableName(columnName), defaultValue); + } + public override bool AddColumnRemark(string columnName, string tableName, string description) + { + tableName = this.SqlBuilder.GetTranslationTableName(tableName); + string sql = string.Format(this.AddColumnRemarkSql, this.SqlBuilder.GetTranslationColumnName(columnName), tableName, description); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + public override bool AddTableRemark(string tableName, string description) + { + tableName = this.SqlBuilder.GetTranslationTableName(tableName); + return base.AddTableRemark(tableName, description); + } + public override bool UpdateColumn(string tableName, DbColumnInfo columnInfo) + { + tableName = this.SqlBuilder.GetTranslationTableName(tableName); + var columnName = this.SqlBuilder.GetTranslationColumnName(columnInfo.DbColumnName); + string sql = GetUpdateColumnSql(tableName, columnInfo); + this.Context.Ado.ExecuteCommand(sql); + var isnull = columnInfo.IsNullable ? " DROP NOT NULL " : " SET NOT NULL "; + this.Context.Ado.ExecuteCommand(string.Format("alter table {0} alter {1} {2}", tableName, columnName, isnull)); + return true; + } + + protected override string GetUpdateColumnSql(string tableName, DbColumnInfo columnInfo) + { + string columnName = this.SqlBuilder.GetTranslationColumnName(columnInfo.DbColumnName); + tableName = this.SqlBuilder.GetTranslationTableName(tableName); + string dataSize = GetSize(columnInfo); + string dataType = columnInfo.DataType; + if (!string.IsNullOrEmpty(dataType)) + { + dataType = " type " + dataType; + } + string nullType = ""; + string primaryKey = null; + string identity = null; + string result = string.Format(this.AlterColumnToTableSql, tableName, columnName, dataType, dataSize, nullType, primaryKey, identity); + return result; + } + + /// + ///by current connection string + /// + /// + /// + public override bool CreateDatabase(string databaseName, string databaseDirectory = null) + { + if (databaseDirectory != null) + { + if (!FileHelper.IsExistDirectory(databaseDirectory)) + { + FileHelper.CreateDirectory(databaseDirectory); + } + } + // var oldDatabaseName = this.Context.Ado.Connection.Database; + //var connection = this.Context.CurrentConnectionConfig.ConnectionString; + //connection = connection.Replace(oldDatabaseName, ""); + if (this.Context.Ado.IsValidConnection()) + { + return true; + } + var newDb = this.Context.CopyNew(); + newDb.Ado.Connection.ChangeDatabase("highgo"); + newDb.Open(); + if (!GetDataBaseList(newDb).Any(it => it.Equals(databaseName, StringComparison.CurrentCultureIgnoreCase))) + { + newDb.Ado.ExecuteCommand(string.Format(CreateDataBaseSql, this.SqlBuilder.SqlTranslationLeft + databaseName + this.SqlBuilder.SqlTranslationRight, databaseDirectory)); + } + newDb.Close(); + return true; + } + public override bool AddRemark(EntityInfo entity) + { + var db = this.Context; + var columns = entity.Columns.Where(it => it.IsIgnore == false).ToList(); + + foreach (var item in columns) + { + if (item.ColumnDescription != null) + { + db.DbMaintenance.AddColumnRemark(item.DbColumnName, item.DbTableName, item.ColumnDescription); + + } + } + //table remak + if (entity.TableDescription != null) + { + db.DbMaintenance.AddTableRemark(entity.DbTableName, entity.TableDescription); + } + return true; + } + public override bool CreateTable(string tableName, List columns, bool isCreatePrimaryKey = true) + { + if (columns.HasValue()) + { + foreach (var item in columns) + { + if (item.DbColumnName.Equals("GUID", StringComparison.CurrentCultureIgnoreCase) && item.Length == 0) + { + item.Length = 10; + } + } + } + string sql = GetCreateTableSql(tableName, columns); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + protected override string GetCreateTableSql(string tableName, List columns) + { + List columnArray = new List(); + Check.Exception(columns.IsNullOrEmpty(), "No columns found "); + foreach (var item in columns) + { + string columnName = item.DbColumnName; + string dataType = item.DataType; + if (dataType == "varchar" && item.Length == 0) + { + item.Length = 1; + } + //if (dataType == "uuid") + //{ + // item.Length = 50; + // dataType = "varchar"; + //} + string dataSize = item.Length > 0 ? string.Format("({0})", item.Length) : null; + if (item.DecimalDigits > 0 && item.Length > 0 && dataType == "numeric") + { + dataSize = $"({item.Length},{item.DecimalDigits})"; + } + string nullType = item.IsNullable ? this.CreateTableNull : CreateTableNotNull; + string primaryKey = item.IsPrimarykey ? CreateTablePirmaryKey : null; + string identity = item.IsIdentity ? CreateTableIdentity : null; + string addItem = string.Format(this.CreateTableColumn, this.SqlBuilder.GetTranslationColumnName(columnName.ToUpper()), dataType, dataSize, nullType, identity, primaryKey); + columnArray.Add(addItem); + } + string tableString = string.Format(this.CreateTableSql, this.SqlBuilder.GetTranslationTableName(tableName), string.Join(",\r\n", columnArray)); + return tableString; + } + public override bool IsAnyConstraint(string constraintName) + { + throw new NotSupportedException("PgSql IsAnyConstraint NotSupportedException"); + } + public override bool BackupDataBase(string databaseName, string fullFileName) + { + Check.ThrowNotSupportedException("PgSql BackupDataBase NotSupported"); + return false; + } + + public override List GetColumnInfosByTableName(string tableName, bool isCache = true) + { + var result = base.GetColumnInfosByTableName(tableName.TrimEnd('"').TrimStart('"').ToLower(), isCache); + if (result == null || result.Count() == 0) + { + result = base.GetColumnInfosByTableName(tableName, isCache); + } + try + { + string sql = $@"SELECT CONSTNAME AS key_column FROM SYSCAT.KEYCOLUSE WHERE TABSCHEMA ='{GetSchema()}' AND TABNAME ='{tableName}'"; + List pkList = new List(); + if (isCache) + { + pkList = GetListOrCache("GetColumnInfosByTableName_N_Pk" + tableName, sql); + } + else + { + pkList = this.Context.Ado.SqlQuery(sql); + } + if (pkList.Count > 1) + { + foreach (var item in result) + { + if (pkList.Select(it => it.ToUpper()).Contains(item.DbColumnName.ToUpper())) + { + item.IsPrimarykey = true; + } + } + } + } + catch + { + + } + return result; + } + #endregion + + #region Helper + + private string GetSchema() + { + var schema = "db2inst1"; + if (System.Text.RegularExpressions.Regex.IsMatch(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), "database=")) + { + var regValue = System.Text.RegularExpressions.Regex.Match(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), @"database\=(\w+)").Groups[1].Value; + if (regValue.HasValue()) + { + schema = regValue; + } + } + return schema; + } + + #endregion + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/Insertable/DB2Inserttable.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/Insertable/DB2Inserttable.cs new file mode 100644 index 000000000..eabeb9ecc --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/Insertable/DB2Inserttable.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.DB2 +{ + public class DB2Inserttable : InsertableProvider where T : class, new() + { + public override int ExecuteReturnIdentity() + { + InsertBuilder.IsReturnIdentity = true; + PreToSql(); + string identityColumn = GetIdentityColumn(); + string sql = InsertBuilder.ToSqlString().Replace("$PrimaryKey", this.SqlBuilder.GetTranslationColumnName(identityColumn)); + RestoreMapping(); + var result = Ado.GetScalar(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray()).ObjToInt(); + After(sql, result); + return result; + } + public override async Task ExecuteReturnIdentityAsync() + { + InsertBuilder.IsReturnIdentity = true; + PreToSql(); + string identityColumn = GetIdentityColumn(); + string sql = InsertBuilder.ToSqlString().Replace("$PrimaryKey", this.SqlBuilder.GetTranslationColumnName(identityColumn)); + RestoreMapping(); + var obj = await Ado.GetScalarAsync(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray()); + var result = obj.ObjToInt(); + After(sql, result); + return result; + } + public override KeyValuePair> ToSql() + { + var result= base.ToSql(); + var primaryKey = GetPrimaryKeys().FirstOrDefault(); + if (primaryKey != null) + { + primaryKey = this.SqlBuilder.GetTranslationColumnName(primaryKey); + } + return new KeyValuePair>(result.Key.Replace("$PrimaryKey", primaryKey), result.Value); + } + + public override long ExecuteReturnBigIdentity() + { + InsertBuilder.IsReturnIdentity = true; + PreToSql(); + string sql = InsertBuilder.ToSqlString().Replace("$PrimaryKey", this.SqlBuilder.GetTranslationColumnName(GetIdentityKeys().FirstOrDefault())); + RestoreMapping(); + var result = Convert.ToInt64(Ado.GetScalar(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray()) ?? "0"); + After(sql, result); + return result; + } + public override async Task ExecuteReturnBigIdentityAsync() + { + InsertBuilder.IsReturnIdentity = true; + PreToSql(); + string sql = InsertBuilder.ToSqlString().Replace("$PrimaryKey", this.SqlBuilder.GetTranslationColumnName(GetIdentityKeys().FirstOrDefault())); + RestoreMapping(); + var result = Convert.ToInt64(await Ado.GetScalarAsync(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray()) ?? "0"); + After(sql, result); + return result; + } + + public override bool ExecuteCommandIdentityIntoEntity() + { + var result = InsertObjs.First(); + var identityKeys = GetIdentityKeys(); + if (identityKeys.Count == 0) { return this.ExecuteCommand() > 0; } + var idValue = ExecuteReturnBigIdentity(); + Check.Exception(identityKeys.Count > 1, "ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); + var identityKey = identityKeys.First(); + object setValue = 0; + if (idValue > int.MaxValue) + setValue = idValue; + else + setValue = Convert.ToInt32(idValue); + var propertyName = this.Context.EntityMaintenance.GetPropertyName(identityKey); + typeof(T).GetProperties().First(t => t.Name.ToUpper() == propertyName.ToUpper()).SetValue(result, setValue, null); + return idValue > 0; + } + + private string GetIdentityColumn() + { + var identityColumn = GetIdentityKeys().FirstOrDefault(); + if (identityColumn == null) + { + var columns = this.Context.DbMaintenance.GetColumnInfosByTableName(InsertBuilder.GetTableNameString); + identityColumn = columns.First(it => it.IsIdentity || it.IsPrimarykey).DbColumnName; + } + return identityColumn; + } + + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/Queryable/DB2Queryable.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/Queryable/DB2Queryable.cs new file mode 100644 index 000000000..dde8167c2 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/Queryable/DB2Queryable.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.DB2 +{ + public class DB2Queryable : QueryableProvider + { + public override ISugarQueryable With(string withString) + { + return this; + } + + public override ISugarQueryable PartitionBy(string groupFileds) + { + this.GroupBy(groupFileds); + return this; + } + } + public class DB2Queryable : QueryableProvider + { + public new ISugarQueryable With(string withString) + { + return this; + } + } + public class DB2Queryable : QueryableProvider + { + + } + public class DB2Queryable : QueryableProvider + { + + } + public class DB2Queryable : QueryableProvider + { + + } + public class DB2Queryable : QueryableProvider + { + + } + public class DB2Queryable : QueryableProvider + { + + } + public class DB2Queryable : QueryableProvider + { + + } + public class DB2Queryable : QueryableProvider + { + + } + public class DB2Queryable : QueryableProvider + { + + } + public class DB2Queryable : QueryableProvider + { + + } + public class DB2Queryable : QueryableProvider + { + + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2Builder.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2Builder.cs new file mode 100644 index 000000000..49f77a05c --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2Builder.cs @@ -0,0 +1,116 @@ +using System; +using System.Linq; +using System.Text.RegularExpressions; + +namespace SqlSugar.DB2 +{ + public class DB2Builder : SqlBuilderProvider + { + public override string SqlTranslationLeft + { + get + { + return " "; + } + } + public override string SqlTranslationRight + { + get + { + return " "; + } + } + public override string SqlDateNow + { + get + { + return "current_date"; + } + } + public override string FullSqlDateNow + { + get + { + return "select current_date"; + } + } + + public bool isAutoToLower + { + get + { + if (this.Context.CurrentConnectionConfig.MoreSettings == null) return true; + return this.Context.CurrentConnectionConfig.MoreSettings.PgSqlIsAutoToLower; + } + } + public override string GetTranslationColumnName(string propertyName) + { + return GetTranslationLeftRigthSql(propertyName.ToUpper()); + } + + //public override string GetNoTranslationColumnName(string name) + //{ + // return name.TrimEnd(Convert.ToChar(SqlTranslationRight)).TrimStart(Convert.ToChar(SqlTranslationLeft)).ToLower(); + //} + public override string GetTranslationColumnName(string entityName, string propertyName) + { + Check.ArgumentNullException(entityName, string.Format(ErrorMessage.ObjNotExist, "Table Name")); + Check.ArgumentNullException(propertyName, string.Format(ErrorMessage.ObjNotExist, "Column Name")); + var context = this.Context; + var mappingInfo = context + .MappingColumns + .FirstOrDefault(it => + it.EntityName.Equals(entityName, StringComparison.CurrentCultureIgnoreCase) && + it.PropertyName.Equals(propertyName, StringComparison.CurrentCultureIgnoreCase)); + return (mappingInfo == null ? SqlTranslationLeft + propertyName.ToUpper() + SqlTranslationRight : SqlTranslationLeft + mappingInfo.DbColumnName.ToUpper() + SqlTranslationRight); + } + + private string GetTranslationLeftRigthSql(string sql) + { + return SqlTranslationLeft + sql + SqlTranslationRight; + } + + public override string GetTranslationTableName(string name) + { + Check.ArgumentNullException(name, string.Format(ErrorMessage.ObjNotExist, "Table Name")); + if (name.Contains(".")) + { + var tableNameArray = name.Split('.'); + for (int i = 0; i < tableNameArray.Length; i++) + { + tableNameArray[i] = i + 1 >= tableNameArray.Length ? GetTranslationLeftRigthSql(tableNameArray[i].ToUpper()) : GetTranslationLeftRigthSql(tableNameArray[i]); + } + return string.Join(".", tableNameArray); + } + + var context = this.Context; + var mappingInfo = context + .MappingTables + .FirstOrDefault(it => it.EntityName.Equals(name, StringComparison.CurrentCultureIgnoreCase)); + name = (mappingInfo == null ? name.ToUpper() : mappingInfo.DbTableName); + return GetTranslationLeftRigthSql(name); + } + public override string GetUnionFomatSql(string sql) + { + return " ( " + sql + " ) "; + } + + public override Type GetNullType(string tableName, string columnName) + { + if (tableName != null) + tableName = tableName.Trim(); + var columnInfo = this.Context.DbMaintenance.GetColumnInfosByTableName(tableName).FirstOrDefault(z => z.DbColumnName?.ToLower() == columnName?.ToLower()); + if (columnInfo != null) + { + var cTypeName = this.Context.Ado.DbBind.GetCsharpTypeNameByDbTypeName(columnInfo.DataType); + var value = SqlSugar.UtilMethods.GetTypeByTypeName(cTypeName); + if (value != null) + { + var key = "GetNullType_" + tableName + columnName; + return new ReflectionInoCacheService().GetOrCreate(key, () => value); + } + } + return null; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2DeleteBuilder.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2DeleteBuilder.cs new file mode 100644 index 000000000..0e67a16a8 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2DeleteBuilder.cs @@ -0,0 +1,7 @@ +namespace SqlSugar.DB2 +{ + public class DB2DeleteBuilder : DeleteBuilder + { + + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2ExpressionContext.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2ExpressionContext.cs new file mode 100644 index 000000000..aee5a209c --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2ExpressionContext.cs @@ -0,0 +1,483 @@ +using System; +using System.Linq; + +namespace SqlSugar.DB2 +{ + public class DB2ExpressionContext : ExpressionContext, ILambdaExpressions + { + public SqlSugarProvider Context { get; set; } + public DB2ExpressionContext() + { + base.DbMehtods = new HGMethod(); + } + public override string SqlTranslationLeft + { + get + { + return ""; + } + } + public override string SqlTranslationRight + { + get + { + return ""; + } + } + public override string GetTranslationText(string name) + { + return SqlTranslationLeft + name.ToUpper() + SqlTranslationRight; + } + + public override string GetTranslationTableName(string entityName, bool isMapping = true) + { + Check.ArgumentNullException(entityName, string.Format(ErrorMessage.ObjNotExist, "Table Name")); + if (IsTranslationText(entityName)) return entityName; + isMapping = isMapping && this.MappingTables.HasValue(); + var isComplex = entityName.Contains(UtilConstants.Dot); + if (isMapping && isComplex) + { + var columnInfo = entityName.Split(UtilConstants.DotChar); + var mappingInfo = this.MappingTables.FirstOrDefault(it => it.EntityName.Equals(columnInfo.Last(), StringComparison.CurrentCultureIgnoreCase)); + if (mappingInfo != null) + { + columnInfo[columnInfo.Length - 1] = mappingInfo.EntityName; + } + return string.Join(UtilConstants.Dot, columnInfo.Select(it => GetTranslationText(it))); + } + else if (isMapping) + { + var mappingInfo = this.MappingTables.FirstOrDefault(it => it.EntityName.Equals(entityName, StringComparison.CurrentCultureIgnoreCase)); + + var tableName = mappingInfo?.DbTableName+""; + if (tableName.Contains(".")) + { + tableName = string.Join(UtilConstants.Dot, tableName.Split(UtilConstants.DotChar).Select(it => GetTranslationText(it))); + return tableName; + } + + return SqlTranslationLeft + (mappingInfo == null ? entityName : mappingInfo.DbTableName).ToUpper() + SqlTranslationRight; + } + else if (isComplex) + { + return string.Join(UtilConstants.Dot, entityName.Split(UtilConstants.DotChar).Select(it => GetTranslationText(it))); + } + else + { + return GetTranslationText(entityName); + } + } + public override string GetTranslationColumnName(string columnName) + { + Check.ArgumentNullException(columnName, string.Format(ErrorMessage.ObjNotExist, "Column Name")); + if (columnName.Substring(0, 1) == this.SqlParameterKeyWord) + { + return columnName; + } + if (IsTranslationText(columnName)) return columnName.ToUpper(); + if (columnName.Contains(UtilConstants.Dot)) + { + return string.Join(UtilConstants.Dot, columnName.Split(UtilConstants.DotChar).Select(it => GetTranslationText(it))); + } + else + { + return GetTranslationText(columnName); + } + } + public override string GetDbColumnName(string entityName, string propertyName) + { + if (this.MappingColumns.HasValue()) + { + var mappingInfo = this.MappingColumns.SingleOrDefault(it => it.EntityName == entityName && it.PropertyName == propertyName); + return (mappingInfo == null ? propertyName : mappingInfo.DbColumnName).ToUpper(); + } + else + { + return propertyName.ToUpper(); + } + } + + public string GetValue(object entityValue) + { + if (entityValue == null) + return null; + var type = UtilMethods.GetUnderType(entityValue.GetType()); + if (UtilConstants.NumericalTypes.Contains(type)) + { + return entityValue.ToString(); + } + else if (type == UtilConstants.DateType) + { + return this.DbMehtods.ToDate(new MethodCallExpressionModel() + { + Args = new System.Collections.Generic.List() { + new MethodCallExpressionArgs(){ MemberName=$"'{entityValue}'" } + } + }); + } + else + { + return this.DbMehtods.ToString(new MethodCallExpressionModel() + { + Args = new System.Collections.Generic.List() { + new MethodCallExpressionArgs(){ MemberName=$"'{entityValue}'" } + } + }); + } + } + } + public class HGMethod : DefaultDbMethod, IDbMethods + { + + public override string GetDateString(string dateValue, string formatString) + { + if (!(formatString?.Contains("24") == true)) + { + formatString = formatString.Replace("HH", "hh24"); + if (!(formatString?.Contains("24") == true)) + { + formatString = formatString.Replace("hh", "hh24"); + } + } + formatString = formatString.Replace("mm", "mi"); + return $"to_char({dateValue},'{formatString}') "; + } + public override string CharIndex(MethodCallExpressionModel model) + { + return string.Format(" (strpos ({1},{0})-1)", model.Args[0].MemberName, model.Args[1].MemberName); + } + public override string TrueValue() + { + return "true"; + } + public override string FalseValue() + { + return "false"; + } + public override string DateDiff(MethodCallExpressionModel model) + { + var parameter = (DateType)(Enum.Parse(typeof(DateType), model.Args[0].MemberValue.ObjToString())); + var begin = model.Args[1].MemberName; + var end = model.Args[2].MemberName; + switch (parameter) + { + case DateType.Year: + return $" ( DATE_PART('Year', {end} ) - DATE_PART('Year', {begin}) )"; + case DateType.Month: + return $" ( ( DATE_PART('Year', {end} ) - DATE_PART('Year', {begin}) ) * 12 + (DATE_PART('month', {end}) - DATE_PART('month', {begin})) )"; + case DateType.Day: + return $" ( DATE_PART('day', {end} - {begin}) )"; + case DateType.Hour: + return $" ( ( DATE_PART('day', {end} - {begin}) ) * 24 + DATE_PART('hour', {end} - {begin} ) )"; + case DateType.Minute: + return $" ( ( ( DATE_PART('day', {end} - {begin}) ) * 24 + DATE_PART('hour', {end} - {begin} ) ) * 60 + DATE_PART('minute', {end} - {begin} ) )"; + case DateType.Second: + return $" ( ( ( DATE_PART('day', {end} - {begin}) ) * 24 + DATE_PART('hour', {end} - {begin} ) ) * 60 + DATE_PART('minute', {end} - {begin} ) ) * 60 + DATE_PART('second', {end} - {begin} )"; + case DateType.Millisecond: + break; + default: + break; + } + throw new Exception(parameter + " datediff no support"); + } + public override string IIF(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var parameter3 = model.Args[2]; + if (parameter.Type == UtilConstants.BoolType) + { + parameter.MemberName = parameter.MemberName.ToString().Replace("=1", "=true"); + parameter2.MemberName = false; + parameter3.MemberName = true; + } + return string.Format("( CASE WHEN {0} THEN {1} ELSE {2} END )", parameter.MemberName, parameter2.MemberName, parameter3.MemberName); + } + public override string DateValue(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var format = "dd"; + if (parameter2.MemberValue.ObjToString() == DateType.Year.ToString()) + { + format = "yyyy"; + } + if (parameter2.MemberValue.ObjToString() == DateType.Month.ToString()) + { + format = "MM"; + } + if (parameter2.MemberValue.ObjToString() == DateType.Day.ToString()) + { + format = "dd"; + } + if (parameter2.MemberValue.ObjToString() == DateType.Hour.ToString()) + { + format = "hh"; + } + if (parameter2.MemberValue.ObjToString() == DateType.Minute.ToString()) + { + format = "mi"; + } + if (parameter2.MemberValue.ObjToString() == DateType.Second.ToString()) + { + format = "ss"; + } + if (parameter2.MemberValue.ObjToString() == DateType.Millisecond.ToString()) + { + format = "ms"; + } + if (parameter2.MemberValue.ObjToString() == DateType.Weekday.ToString()) + { + return $" extract(DOW FROM cast({parameter.MemberName} as TIMESTAMP)) "; + } + + return string.Format(" cast( to_char({1},'{0}')as integer ) ", format, parameter.MemberName); + } + + public override string Contains(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ({0} like concat('%',{1},'%')) ", parameter.MemberName, parameter2.MemberName ); + } + + public override string StartsWith(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ({0} like concat({1},'%')) ", parameter.MemberName, parameter2.MemberName); + } + + public override string EndsWith(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ({0} like concat('%',{1}))", parameter.MemberName,parameter2.MemberName); + } + + public override string DateIsSameDay(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ( to_char({0},'yyyy-MM-dd')=to_char({1},'yyyy-MM-dd') ) ", parameter.MemberName, parameter2.MemberName); ; + } + + public override string HasValue(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format("( {0} IS NOT NULL )", parameter.MemberName); + } + + public override string DateIsSameByType(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var parameter3 = model.Args[2]; + DateType dateType =(DateType)parameter3.MemberValue; + var format = "yyyy-MM-dd"; + if (dateType == DateType.Quarter) + { + return string.Format(" (date_trunc('quarter',{0})=date_trunc('quarter',{1}) ) ", parameter.MemberName, parameter2.MemberName,format); + } + switch (dateType) + { + case DateType.Year: + format = "yyyy"; + break; + case DateType.Month: + format = "yyyy-MM"; + break; + case DateType.Day: + break; + case DateType.Hour: + format = "yyyy-MM-dd HH"; + break; + case DateType.Second: + format = "yyyy-MM-dd HH:mm:ss"; + break; + case DateType.Minute: + format = "yyyy-MM-dd HH:mm"; + break; + case DateType.Millisecond: + format = "yyyy-MM-dd HH:mm.ms"; + break; + default: + break; + } + return string.Format(" ( to_char({0},'{2}')=to_char({1},'{2}') ) ", parameter.MemberName, parameter2.MemberName, format); + } + + public override string ToDate(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS timestamp)", parameter.MemberName); + } + public override string DateAddByType(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var parameter3 = model.Args[2]; + return string.Format(" ({1} + ({2}||'{0}')::INTERVAL) ", parameter3.MemberValue, parameter.MemberName, parameter2.MemberName); + } + + public override string DateAddDay(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ({0} + ({1}||'day')::INTERVAL) ", parameter.MemberName, parameter2.MemberName); + } + + public override string ToInt32(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS INT4)", parameter.MemberName); + } + + public override string ToInt64(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS INT8)", parameter.MemberName); + } + + public override string ToString(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS VARCHAR)", parameter.MemberName); + } + + public override string ToGuid(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS UUID)", parameter.MemberName); + } + + public override string ToDouble(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS DECIMAL(18,4))", parameter.MemberName); + } + + public override string ToBool(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS boolean)", parameter.MemberName); + } + + public override string ToDecimal(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS DECIMAL(18,4))", parameter.MemberName); + } + + public override string Length(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" LENGTH({0})", parameter.MemberName); + } + public override string MergeString(params string[] strings) + { + return " concat("+string.Join(",", strings).Replace("+", "") + ") "; + } + public override string IsNull(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter1 = model.Args[1]; + return string.Format("(CASE WHEN {0} IS NULL THEN {1} ELSE {0} END)", parameter.MemberName, parameter1.MemberName); + } + public override string GetDate() + { + return "NOW()"; + } + public override string GetRandom() + { + return "RANDOM()"; + } + + public override string EqualTrue(string fieldName) + { + return "( " + fieldName + "=true )"; + } + + public override string JsonField(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter1 = model.Args[1]; + //var parameter2 = model.Args[2]; + //var parameter3= model.Args[3]; + var result= GetJson(parameter.MemberName, parameter1.MemberName, model.Args.Count()==2); + if (model.Args.Count > 2) + { + result = GetJson(result, model.Args[2].MemberName, model.Args.Count() == 3); + } + if (model.Args.Count > 3) + { + result = GetJson(result, model.Args[3].MemberName, model.Args.Count() == 4); + } + if (model.Args.Count > 4) + { + result = GetJson(result, model.Args[4].MemberName, model.Args.Count() == 5); + } + if (model.Args.Count > 5) + { + result = GetJson(result, model.Args[5].MemberName, model.Args.Count() == 6); + } + return result; + } + + public override string JsonContainsFieldName(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter1 = model.Args[1]; + return $"({parameter.MemberName}::jsonb ?{parameter1.MemberName})"; + } + + private string GetJson(object memberName1, object memberName2,bool isLast) + { + if (isLast) + { + return $"({memberName1}::json->>{memberName2})"; + } + else + { + return $"({memberName1}->{memberName2})"; + } + } + + public override string JsonArrayLength(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + //var parameter1 = model.Args[1]; + return $" json_array_length({parameter.MemberName}::json) "; + } + + public override string JsonParse(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + //var parameter1 = model.Args[1]; + return $" ({parameter.MemberName}::json) "; + } + + public override string JsonArrayAny(MethodCallExpressionModel model) + { + if (SqlSugar.UtilMethods.IsNumber(model.Args[1].MemberValue.GetType().Name)) + { + return $" {model.Args[0].MemberName}::jsonb @> '[{model.Args[1].MemberValue.ObjToStringNoTrim().ToSqlFilter()}]'::jsonb"; + } + else + { + return $" {model.Args[0].MemberName}::jsonb @> '[\"{model.Args[1].MemberValue}\"]'::jsonb"; + } + } + public override string JsonListObjectAny(MethodCallExpressionModel model) + { + if (SqlSugar.UtilMethods.IsNumber(model.Args[2].MemberValue.GetType().Name)) + { + return $" {model.Args[0].MemberName}::jsonb @> '[{{\"{model.Args[1].MemberValue}\":{model.Args[2].MemberValue}}}]'::jsonb"; + } + else + { + return $" {model.Args[0].MemberName}::jsonb @> '[{{\"{model.Args[1].MemberValue}\":\"{model.Args[2].MemberValue.ObjToStringNoTrim().ToSqlFilter()}\"}}]'::jsonb"; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2FastBuilder.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2FastBuilder.cs new file mode 100644 index 000000000..8cbfd85e8 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2FastBuilder.cs @@ -0,0 +1,149 @@ +using IBM.Data.Db2; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.DB2 +{ + public class DB2FastBuilder : FastBuilder, IFastBuilder + { + public static Dictionary Db2Type = UtilMethods.EnumToDictionary(); + private EntityInfo entityInfo; + + public DB2FastBuilder(EntityInfo entityInfo) + { + this.entityInfo = entityInfo; + } + + public override string UpdateSql { get; set; } = @"UPDATE {1} SET {0} FROM {2} AS TE WHERE {3} +"; + + //public virtual async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) + //{ + // Check.ArgumentNullException(!updateColumns.Any(), "update columns count is 0"); + // Check.ArgumentNullException(!whereColumns.Any(), "where columns count is 0"); + // var sets = string.Join(",", updateColumns.Select(it => $"TM.{it}=TE.{it}")); + // var wheres = string.Join(",", whereColumns.Select(it => $"TM.{it}=TE.{it}")); + // string sql = string.Format(UpdateSql, sets, tableName, tempName, wheres); + // return await this.Context.Ado.ExecuteCommandAsync(sql); + //} + public async Task ExecuteBulkCopyAsync(DataTable dt) + { + List lsColNames = new List(); + for (int i = 0; i < dt.Columns.Count; i++) + { + lsColNames.Add($"\"{dt.Columns[i].ColumnName}\""); + } + string copyString = $"COPY {dt.TableName} ( {string.Join(",", lsColNames) } ) FROM STDIN (FORMAT BINARY)"; + DB2Connection conn = (DB2Connection)this.Context.Ado.Connection; + var columns = this.Context.DbMaintenance.GetColumnInfosByTableName(this.entityInfo.DbTableName); + try + { + var identityColumnInfo = this.entityInfo.Columns.FirstOrDefault(it => it.IsIdentity); + if (identityColumnInfo != null) + { + throw new Exception("PgSql bulkcopy no support identity"); + } + BulkCopy(dt, copyString, conn, columns); + } + catch (Exception ex) + { + throw ex; + } + finally + { + base.CloseDb(); + } + return await Task.FromResult(dt.Rows.Count); + } + + private void BulkCopy(DataTable dt, string copyString, DB2Connection conn, List columns) + { + if (conn.State == ConnectionState.Closed) + conn.Open(); + List columnViews = new List(); + foreach (DataColumn item in dt.Columns) + { + ColumnView result = new ColumnView(); + result.DbColumnInfo = columns.FirstOrDefault(it => it.DbColumnName?.ToLower()==item.ColumnName?.ToLower()); + result.DataColumn = item; + result.EntityColumnInfo=this.entityInfo.Columns.FirstOrDefault(it => it.DbColumnName?.ToLower()==item.ColumnName?.ToLower()); + var key = result.DbColumnInfo?.DataType?.ToLower(); + if (result.DbColumnInfo == null) + { + result.Type = null; + } + else if (Db2Type.ContainsKey(key)) + { + result.Type = Db2Type[key]; + } + else if (key?.First() == '_') + { + var type = Db2Type[key.Substring(1)]; + result.Type = DB2Type.DynArray | type; + } + else + { + result.Type = null; + } + columnViews.Add(result); + } + using (var writer = conn.(copyString)) + { + foreach (DataRow row in dt.Rows) + { + writer.StartRow(); + foreach (var column in columnViews) + { + var value = row[column.DataColumn.ColumnName]; + if (value == null) + { + value = DBNull.Value; + } + else if (value is double) + { + column.Type = DB2Type.Double; + } + if (column.Type == null) + { + writer.Write(value); + } + else + { + writer.Write(value, column.Type.Value); + } + } + } + writer.Close(); + } + } + + + public override async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) + { + var sqlquerybulder= this.Context.Queryable().SqlBuilder; + Check.ArgumentNullException(!updateColumns.Any(), "update columns count is 0"); + Check.ArgumentNullException(!whereColumns.Any(), "where columns count is 0"); + var sets = string.Join(",", updateColumns.Select(it => $"{sqlquerybulder.GetTranslationColumnName(it)}=TE.{sqlquerybulder.GetTranslationColumnName(it)}")); + var wheres = string.Join(" AND ", whereColumns.Select(it => $"{tableName}.{sqlquerybulder.GetTranslationColumnName(it)}=TE.{sqlquerybulder.GetTranslationColumnName(it)}")); + string sql = string.Format(UpdateSql, sets, tableName, tempName, wheres); + return await this.Context.Ado.ExecuteCommandAsync(sql); + } + public override async Task CreateTempAsync(DataTable dt) + { + await this.Context.Queryable().Where(it => false).AS(dt.TableName).Select(" * into temp mytemptable").ToListAsync(); + dt.TableName = "mytemptable"; + } + + public class ColumnView + { + public DataColumn DataColumn { get; set; } + public EntityColumnInfo EntityColumnInfo { get; set; } + public DbColumnInfo DbColumnInfo { get; set; } + public DB2Type? Type { get; set; } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2InsertBuilder.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2InsertBuilder.cs new file mode 100644 index 000000000..4cd7e080f --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2InsertBuilder.cs @@ -0,0 +1,186 @@ +using System; +using System.Linq; +using System.Text; + +namespace SqlSugar.DB2 +{ + public class DB2InsertBuilder : InsertBuilder + { + public override string SqlTemplate + { + get + { + if (IsReturnIdentity) + { + return @"SELECT $PrimaryKey FROM FINAL TABLE ( + INSERT INTO {0} + ({1}) + VALUES + ({2})) "; + } + else + { + return @"INSERT INTO {0} + ({1}) + VALUES + ({2}) ;"; + + } + } + + } + public override string SqlTemplateBatch => "INSERT INTO {0} ({1})"; + public override string SqlTemplateBatchUnion => " VALUES "; + + public override string SqlTemplateBatchSelect => " {0} "; + + public override Func ConvertInsertReturnIdFunc { get; set; } = (name, sql) => + { + return sql.Trim().TrimEnd(';') + $"returning {name} "; + }; + public override string ToSqlString() + { + if (IsNoInsertNull) + { + DbColumnInfoList = DbColumnInfoList.Where(it => it.Value != null).ToList(); + } + var groupList = DbColumnInfoList.GroupBy(it => it.TableId).ToList(); + var isSingle = groupList.Count() == 1; + string columnsString = string.Join(",", groupList.First().Select(it => Builder.GetTranslationColumnName(it.DbColumnName))); + if (isSingle) + { + string columnParametersString = string.Join(",", this.DbColumnInfoList.Select(it => base.GetDbColumn(it, Builder.SqlParameterKeyWord + it.DbColumnName))); + ActionMinDate(); + var executeSql = string.Format(SqlTemplate, GetTableNameString, columnsString, columnParametersString); + if (IsReturnIdentity) + { + var identityColumn = this.EntityInfo.Columns.FirstOrDefault(it => it.IsIdentity); + executeSql = executeSql.Replace("$PrimaryKey", identityColumn.DbColumnName); + } + return executeSql; + } + else + { + StringBuilder batchInsetrSql = new StringBuilder(); + int pageSize = 200; + int pageIndex = 1; + if (IsNoPage && IsReturnPkList) + { + pageSize = groupList.Count; + } + int totalRecord = groupList.Count; + int pageCount = (totalRecord + pageSize - 1) / pageSize; + while (pageCount >= pageIndex) + { + batchInsetrSql.AppendFormat(SqlTemplateBatch, GetTableNameString, columnsString); + int i = 0; + foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList()) + { + var isFirst = i == 0; + if (isFirst) + { + batchInsetrSql.Append(SqlTemplateBatchUnion); + } + batchInsetrSql.Append("\r\n ( " + string.Join(",", columns.Select(it => + { + if (it.InsertServerTime || it.InsertSql.HasValue() || it.SqlParameterDbType is Type || it?.PropertyType?.Name == "DateOnly" || it?.PropertyType?.Name == "TimeOnly") + { + return GetDbColumn(it, null); + } + object value = null; + if (it.Value is DateTime) + { + value = ((DateTime)it.Value).ToString("O"); + } + else if (it.Value is DateTimeOffset) + { + return FormatDateTimeOffset(it.Value); + } + else if (it.IsArray && it.Value != null) + { + return FormatValue(it.Value, it.PropertyName, i, it); + } + else + { + value = it.Value; + } + if (value == null || value == DBNull.Value) + { + return string.Format(SqlTemplateBatchSelect, "NULL"); + } + return string.Format(SqlTemplateBatchSelect, "'" + value.ObjToStringNoTrim().ToSqlFilter() + "'"); + })) + "),"); + ++i; + } + pageIndex++; + batchInsetrSql.Remove(batchInsetrSql.Length - 1, 1).Append("\r\n;\r\n"); + } + return batchInsetrSql.ToString(); + } + } + + public object FormatValue(object value, string name, int i, DbColumnInfo columnInfo) + { + if (value == null) + { + return "NULL"; + } + else + { + var type = value.GetType(); + if (type == UtilConstants.DateType || columnInfo.IsArray || columnInfo.IsJson) + { + var parameterName = this.Builder.SqlParameterKeyWord + name + i; + var paramter = new SugarParameter(parameterName, value); + if (columnInfo.IsJson) + { + paramter.IsJson = true; + } + if (columnInfo.IsArray) + { + paramter.IsArray = true; + } + this.Parameters.Add(paramter); + return parameterName; + } + else if (type == UtilConstants.ByteArrayType) + { + string bytesString = "0x" + BitConverter.ToString((byte[])value); + return bytesString; + } + else if (type.IsEnum()) + { + if (this.Context.CurrentConnectionConfig.MoreSettings?.TableEnumIsString == true) + { + return value.ToSqlValue(); + } + else + { + return Convert.ToInt64(value); + } + } + else if (type == UtilConstants.DateTimeOffsetType) + { + return FormatDateTimeOffset(value); + } + else if (type == UtilConstants.BoolType) + { + return value.ObjToBool() ? "1" : "0"; + } + else if (type == UtilConstants.StringType || type == UtilConstants.ObjType) + { + return "'" + value.ToString().ToSqlFilter() + "'"; + } + else + { + return "'" + value.ToString() + "'"; + } + } + } + public override string FormatDateTimeOffset(object value) + { + return "'" + ((DateTimeOffset)value).ToString("o") + "'"; + } + + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2QueryBuilder.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2QueryBuilder.cs new file mode 100644 index 000000000..4686bea10 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2QueryBuilder.cs @@ -0,0 +1,143 @@ +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace SqlSugar.DB2 +{ + public partial class DB2QueryBuilder : QueryBuilder + { + #region Sql Template + public override string PageTempalte + { + get + { + /* + SELECT * FROM TABLE WHERE CONDITION ORDER BY ID DESC LIMIT 10 offset 0 + */ + var template = "SELECT {0} FROM {1} {2} {3} {4} LIMIT {6} offset {5}"; + return template; + } + } + public override string DefaultOrderByTemplate + { + get + { + return "ORDER BY NOW() "; + } + } + + #endregion + + #region Common Methods + public override string GetTableNameString + { + get + { + if (this.TableShortName != null) + { + this.TableShortName = Builder.GetTranslationColumnName(this.TableShortName); + } + return base.GetTableNameString; + } + } + + //public override string GetWhereValueString + //{ + // get + // { + // return base.GetWhereValueString.Replace("\"", "".ToUpper()); ; + // } + //} + + //public override string GetJoinValueString + //{ + // get + // { + // if (this.JoinQueryInfos.IsNullOrEmpty()) return null; + // else + // { + // return string.Join(UtilConstants.Space, this.JoinQueryInfos.Select(it => this.ToJoinString(it).Replace("\"", "").ToUpper())); + // } + // } + //} + + public override bool IsComplexModel(string sql) + { + return Regex.IsMatch(sql, @"AS ""\w+\.\w+""") || Regex.IsMatch(sql, @"AS ""\w+\.\w+\.\w+"""); + } + public override string ToSqlString() + { + base.AppendFilter(); + string oldOrderValue = this.OrderByValue; + string result = null; + sql = new StringBuilder(); + sql.AppendFormat(SqlTemplate, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, (Skip != null || Take != null) ? null : GetOrderByString); + if (IsCount) { return sql.ToString(); } + if (Skip != null && Take == null) + { + if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0]; + result = string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, (Skip != null || Take != null) ? null : GetOrderByString, Skip.ObjToInt(), long.MaxValue); + } + else if (Skip == null && Take != null) + { + if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0]; + result = string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, GetOrderByString, 0, Take.ObjToInt()); + } + else if (Skip != null && Take != null) + { + if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0]; + result = string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, GetOrderByString, Skip.ObjToInt() > 0 ? Skip.ObjToInt() : 0, Take); + } + else + { + result = sql.ToString(); + } + this.OrderByValue = oldOrderValue; + result = GetSqlQuerySql(result); + if (result.IndexOf("-- No table") > 0) + { + return "-- No table"; + } + if (TranLock != null) + { + result = result + TranLock; + } + return result; + } + + #endregion + + #region Get SQL Partial + public override string GetSelectValue + { + get + { + string result = string.Empty; + if (this.SelectValue == null || this.SelectValue is string) + { + result = GetSelectValueByString(); + } + else + { + result = GetSelectValueByExpression(); + } + if (this.SelectType == ResolveExpressType.SelectMultiple) + { + this.SelectCacheKey = this.SelectCacheKey + string.Join("-", this.JoinQueryInfos.Select(it => it.TableName)); + } + if (IsDistinct) + { + result = "distinct " + result; + } + if (this.SubToListParameters != null && this.SubToListParameters.Any()) + { + result = SubToListMethod(result); + } + return result; + //return result.Replace("\"", "").ToUpper(); + } + } + + #endregion + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2UpdateBuilder.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2UpdateBuilder.cs new file mode 100644 index 000000000..e0c62f404 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2/SqlBuilder/DB2UpdateBuilder.cs @@ -0,0 +1,249 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar.DB2 +{ + public class DB2UpdateBuilder : UpdateBuilder + { + public override string SqlTemplateBatch + { + get + { + return @"UPDATE {1} {2} SET {0} FROM ${{0}} "; + } + } + public override string SqlTemplateJoin + { + get + { + return @" (VALUES + {0} + + ) AS T ({2}) WHERE {1} + "; + } + } + + public override string SqlTemplateBatchUnion + { + get + { + return ","; + } + } + + public object FormatValue(object value,string name,int i,DbColumnInfo columnInfo) + { + if (value == null) + { + return "NULL"; + } + else + { + var type =UtilMethods.GetUnderType(value.GetType()); + if (type == UtilConstants.DateType||columnInfo.IsArray||columnInfo.IsJson) + { + var parameterName = this.Builder.SqlParameterKeyWord + name + i; + var paramter = new SugarParameter(parameterName, value); + if (columnInfo.IsJson) + { + paramter.IsJson = true; + } + if (columnInfo.IsArray) + { + paramter.IsArray = true; + } + this.Parameters.Add(paramter); + return parameterName; + } + else if (type == UtilConstants.DateTimeOffsetType) + { + return FormatDateTimeOffset(value); + } + else if (type == UtilConstants.ByteArrayType) + { + string bytesString = "0x" + BitConverter.ToString((byte[])value); + return bytesString; + } + else if (type.IsEnum()) + { + if (this.Context.CurrentConnectionConfig.MoreSettings?.TableEnumIsString == true) + { + return value.ToSqlValue(); + } + else + { + return Convert.ToInt64(value); + } + } + else if (type == UtilConstants.BoolType) + { + return value.ObjToBool() ? "1" : "0"; + } + else if (type == UtilConstants.StringType || type == UtilConstants.ObjType) + { + return "'" + value.ToString().ToSqlFilter() + "'"; + } + else + { + return "'" + value.ToString() + "'"; + } + } + } + + protected override string TomultipleSqlString(List> groupList) + { + Check.Exception(PrimaryKeys == null || PrimaryKeys.Count == 0, " Update List need Primary key"); + int pageSize = 200; + int pageIndex = 1; + int totalRecord = groupList.Count; + int pageCount = (totalRecord + pageSize - 1) / pageSize; + StringBuilder batchUpdateSql = new StringBuilder(); + while (pageCount >= pageIndex) + { + StringBuilder updateTable = new StringBuilder(); + string setValues = string.Join(",", groupList.First().Where(it => it.IsPrimarykey == false && (it.IsIdentity == false || (IsOffIdentity && it.IsIdentity))).Select(it => + { + if (SetValues.IsValuable()) + { + var setValue = SetValues.Where(sv => sv.Key == Builder.GetTranslationColumnName(it.DbColumnName)); + if (setValue != null && setValue.Any()) + { + return setValue.First().Value; + } + } + var result = string.Format("{0}=T.{0}", Builder.GetTranslationColumnName(it.DbColumnName)); + return result; + })); + string tempColumnValue = string.Join(",", groupList.First().Select(it => + { + if (SetValues.IsValuable()) + { + var setValue = SetValues.Where(sv => sv.Key == Builder.GetTranslationColumnName(it.DbColumnName)); + if (setValue != null && setValue.Any()) + { + return setValue.First().Value; + } + } + var result = Builder.GetTranslationColumnName(it.DbColumnName); + return result; + })); + batchUpdateSql.AppendFormat(SqlTemplateBatch.ToString(), setValues, GetTableNameStringNoWith, TableWithString); + int i = 0; + var tableColumnList = this.Context.DbMaintenance.GetColumnInfosByTableName(GetTableNameStringNoWith); + + foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList()) + { + var isFirst = i == 0; + if (!isFirst) + { + updateTable.Append(SqlTemplateBatchUnion); + } + updateTable.Append("\r\n (" + string.Join(",", columns.Select(it => + { + var columnInfo = tableColumnList.FirstOrDefault(x => x.DbColumnName.Equals(it.DbColumnName, StringComparison.OrdinalIgnoreCase)); + var dbType = columnInfo?.DataType; + if (dbType == null) { + var typeName = it.PropertyType.Name.ToLower(); + if (columnInfo==null&&it.PropertyType.IsEnum) + { + if (this.Context.CurrentConnectionConfig?.MoreSettings?.TableEnumIsString!=true) + { + typeName = "int"; + } + } + if (typeName == "int32") + typeName = "int"; + if (typeName == "int64") + typeName = "long"; + if (typeName == "int16") + typeName = "short"; + if (typeName == "boolean") + typeName = "bool"; + + var isAnyType = DB2DbBind.MappingTypesConst.Where(x => x.Value.ToString().ToLower() == typeName).Any(); + if (isAnyType) + { + dbType = DB2DbBind.MappingTypesConst.Where(x => x.Value.ToString().ToLower() == typeName).FirstOrDefault().Key; + } + else { + dbType = "varchar"; + } + } + return string.Format("CAST({0} AS {1})", base.GetDbColumn(it,FormatValue(it.Value,it.DbColumnName,i,it)), dbType); + + })) + ")"); + ++i; + } + pageIndex++; + updateTable.Append("\r\n"); + string whereString = null; + if (this.WhereValues.HasValue()) + { + foreach (var item in WhereValues) + { + var isFirst = whereString == null; + whereString += (isFirst ? null : " AND "); + whereString += item; + } + } + else if (PrimaryKeys.HasValue()) + { + foreach (var item in PrimaryKeys) + { + var isFirst = whereString == null; + whereString += (isFirst ? null : " AND "); + whereString += string.Format("{0}.{1}=T.{1}", GetTableNameStringNoWith, Builder.GetTranslationColumnName(item)); + } + } + var format = string.Format(SqlTemplateJoin, updateTable, whereString, tempColumnValue); + batchUpdateSql.Replace("${0}", format); + batchUpdateSql.Append(";"); + } + batchUpdateSql = GetBatchUpdateSql(batchUpdateSql); + return batchUpdateSql.ToString(); + } + + private StringBuilder GetBatchUpdateSql(StringBuilder batchUpdateSql) + { + if (ReSetValueBySqlExpListType == null && ReSetValueBySqlExpList != null) + { + var result = batchUpdateSql.ToString(); + foreach (var item in ReSetValueBySqlExpList) + { + var dbColumnName = item.Value.DbColumnName; + if (item.Value.Type == ReSetValueBySqlExpListModelType.List) + { + result = result.Replace($"{dbColumnName}=T.{dbColumnName}", $"{dbColumnName}={GetTableNameString}.{dbColumnName}{item.Value.Sql}T.{dbColumnName}"); + } + else + { + result = result.Replace($"{dbColumnName}=T.{dbColumnName}", $"{dbColumnName}={item.Value.Sql.Replace(dbColumnName, $"{Builder.GetTranslationColumnName(this.TableName)}.{dbColumnName}")}"); + } + batchUpdateSql = new StringBuilder(result); + } + } + + return batchUpdateSql; + } + protected override string GetJoinUpdate(string columnsString, ref string whereString) + { + var formString = $" {Builder.GetTranslationColumnName(this.TableName)} AS {Builder.GetTranslationColumnName(this.ShortName)} "; + var joinString = ""; + foreach (var item in this.JoinInfos) + { + whereString += " AND "+item.JoinWhere; + joinString += $"\r\n FROM {Builder.GetTranslationColumnName(item.TableName)} {Builder.GetTranslationColumnName(item.ShortName)} "; + } + var tableName = formString + "\r\n "; + columnsString = columnsString.Replace(Builder.GetTranslationColumnName(this.ShortName)+".","")+joinString; + return string.Format(SqlTemplate, tableName, columnsString, whereString); + } + public override string FormatDateTimeOffset(object value) + { + return "'" + ((DateTimeOffset)value).ToString("o") + "'"; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2DataAdapter.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2DataAdapter.cs new file mode 100644 index 000000000..02fd0fcba --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/DB2DataAdapter.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Text; +using IBM.Data.Db2; + +namespace SqlSugar.DB2 +{ + /// + /// 数据填充器 + /// + public class DB2DataAdapter : IDataAdapter + { + private DB2Command command; + private string sql; + private DB2Connection _sqlConnection; + + /// + /// SqlDataAdapter + /// + /// + public DB2DataAdapter(DB2Command command) + { + this.command = command; + } + + public DB2DataAdapter() + { + + } + + /// + /// SqlDataAdapter + /// + /// + /// + public DB2DataAdapter(string sql, DB2Connection _sqlConnection) + { + this.sql = sql; + this._sqlConnection = _sqlConnection; + } + + /// + /// SelectCommand + /// + public DB2Command SelectCommand + { + get + { + if (this.command == null) + { + this.command = new DB2Command(this.sql, this._sqlConnection); + } + return this.command; + } + set + { + this.command = value; + } + } + + /// + /// Fill + /// + /// + public void Fill(DataTable dt) + { + if (dt == null) + { + dt = new DataTable(); + } + var columns = dt.Columns; + var rows = dt.Rows; + using (DB2DataReader dr = command.ExecuteReader()) + { + for (int i = 0; i < dr.FieldCount; i++) + { + string name = dr.GetName(i).Trim(); + if (!columns.Contains(name)) + columns.Add(new DataColumn(name, dr.GetFieldType(i))); + else + { + columns.Add(new DataColumn(name + i, dr.GetFieldType(i))); + } + } + + while (dr.Read()) + { + DataRow daRow = dt.NewRow(); + for (int i = 0; i < columns.Count; i++) + { + daRow[columns[i].ColumnName] = dr.GetValue(i); + } + dt.Rows.Add(daRow); + } + } + dt.AcceptChanges(); + } + + /// + /// Fill + /// + /// + public void Fill(DataSet ds) + { + if (ds == null) + { + ds = new DataSet(); + } + using (DB2DataReader dr = command.ExecuteReader()) + { + do + { + var dt = new DataTable(); + var columns = dt.Columns; + var rows = dt.Rows; + for (int i = 0; i < dr.FieldCount; i++) + { + string name = dr.GetName(i).Trim(); + if (!columns.Contains(name)) + columns.Add(new DataColumn(name, dr.GetFieldType(i))); + else + { + columns.Add(new DataColumn(name + i, dr.GetFieldType(i))); + } + } + + while (dr.Read()) + { + DataRow daRow = dt.NewRow(); + for (int i = 0; i < columns.Count; i++) + { + daRow[columns[i].ColumnName] = dr.GetValue(i); + } + dt.Rows.Add(daRow); + } + dt.AcceptChanges(); + ds.Tables.Add(dt); + } while (dr.NextResult()); + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/SqlSugar.Db2Core.csproj b/Src/Asp.NetCore2/SqlSugar.Db2Core/SqlSugar.Db2Core.csproj new file mode 100644 index 000000000..5ab160c10 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/SqlSugar.Db2Core.csproj @@ -0,0 +1,27 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + + + + + + diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/ErrorMessage.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/ErrorMessage.cs new file mode 100644 index 000000000..6523c2c5a --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/ErrorMessage.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar.DB2 +{ + internal static partial class ErrorMessage + { + internal static LanguageType SugarLanguageType { get; set; } = LanguageType.Default; + internal static string ObjNotExist + { + get + { + return GetThrowMessage("{0} does not exist.", + "{0}不存在。"); + } + } + internal static string EntityMappingError + { + get + { + return GetThrowMessage("Entity mapping error.{0}", + "实体与表映射出错。{0}"); + } + } + + public static string NotSupportedDictionary + { + get + { + return GetThrowMessage("This type of Dictionary is not supported for the time being. You can try Dictionary, or contact the author!!", + "暂时不支持该类型的Dictionary 你可以试试 Dictionary或者联系作者!!"); + } + } + + public static string NotSupportedArray + { + get + { + return GetThrowMessage("This type of Array is not supported for the time being. You can try object[] or contact the author!!", + "暂时不支持该类型的Array 你可以试试 object[] 或者联系作者!!"); + } + } + + internal static string GetThrowMessage(string enMessage, string cnMessage, params string[] args) + { + if (SugarLanguageType == LanguageType.Default) + { + List formatArgs = new List() { enMessage, cnMessage }; + formatArgs.AddRange(args); + return string.Format(@"中文提示 : {1} +English Message : {0}", formatArgs.ToArray()); + } + else if (SugarLanguageType == LanguageType.English) + { + return enMessage; + } + else + { + return cnMessage; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/FileHelper.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/FileHelper.cs new file mode 100644 index 000000000..411824796 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/FileHelper.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace SqlSugar.DB2 +{ + internal class FileHelper + { + public static void CreateFile(string filePath, string text, Encoding encoding) + { + try + { + if (IsExistFile(filePath)) + { + DeleteFile(filePath); + } + if (!IsExistFile(filePath)) + { + string directoryPath = GetDirectoryFromFilePath(filePath); + CreateDirectory(directoryPath); + + //Create File + FileInfo file = new FileInfo(filePath); + using (FileStream stream = file.Create()) + { + using (StreamWriter writer = new StreamWriter(stream, encoding)) + { + writer.Write(text); + writer.Flush(); + } + } + } + } + catch(Exception ex) + { + throw ex; + } + } + public static bool IsExistDirectory(string directoryPath) + { + return Directory.Exists(directoryPath); + } + public static void CreateDirectory(string directoryPath) + { + if (!IsExistDirectory(directoryPath)) + { + Directory.CreateDirectory(directoryPath); + } + } + public static void DeleteFile(string filePath) + { + if (IsExistFile(filePath)) + { + File.Delete(filePath); + } + } + public static string GetDirectoryFromFilePath(string filePath) + { + FileInfo file = new FileInfo(filePath); + DirectoryInfo directory = file.Directory; + return directory.FullName; + } + public static bool IsExistFile(string filePath) + { + return File.Exists(filePath); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/UtilConstants.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/UtilConstants.cs new file mode 100644 index 000000000..eef2a814a --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/UtilConstants.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Text; +namespace SqlSugar.DB2 +{ + internal static class UtilConstants + { + public const string Dot = "."; + public const char DotChar = '.'; + internal const string Space = " "; + internal const char SpaceChar =' '; + internal const string AssemblyName = "SqlSugar"; + internal const string ReplaceKey = "{662E689B-17A1-4D06-9D27-F29EAB8BC3D6}"; + internal const string ReplaceCommaKey = "{112A689B-17A1-4A06-9D27-A39EAB8BC3D5}"; + + internal static Type IntType = typeof(int); + internal static Type LongType = typeof(long); + internal static Type GuidType = typeof(Guid); + internal static Type BoolType = typeof(bool); + internal static Type BoolTypeNull = typeof(bool?); + internal static Type ByteType = typeof(Byte); + internal static Type ObjType = typeof(object); + internal static Type DobType = typeof(double); + internal static Type FloatType = typeof(float); + internal static Type ShortType = typeof(short); + internal static Type DecType = typeof(decimal); + internal static Type StringType = typeof(string); + internal static Type DateType = typeof(DateTime); + internal static Type DateTimeOffsetType = typeof(DateTimeOffset); + internal static Type TimeSpanType = typeof(TimeSpan); + internal static Type ByteArrayType = typeof(byte[]); + internal static Type ModelType= typeof(ModelContext); + internal static Type DynamicType = typeof(ExpandoObject); + internal static Type Dicii = typeof(KeyValuePair); + internal static Type DicIS = typeof(KeyValuePair); + internal static Type DicSi = typeof(KeyValuePair); + internal static Type DicSS = typeof(KeyValuePair); + internal static Type DicOO = typeof(KeyValuePair); + internal static Type DicSo = typeof(KeyValuePair); + internal static Type DicArraySS = typeof(Dictionary); + internal static Type DicArraySO = typeof(Dictionary); + + public static Type SugarType = typeof(SqlSugarProvider); + + + internal static Type[] NumericalTypes = new Type[] + { + typeof(int), + typeof(uint), + typeof(byte), + typeof(sbyte), + typeof(long), + typeof(ulong), + typeof(short), + typeof(ushort), + }; + + + internal static string[] DateTypeStringList = new string[] + { + "Year", + "Month", + "Day", + "Hour", + "Second" , + "Minute", + "Millisecond", + "Date" + }; + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/UtilExtensions.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/UtilExtensions.cs new file mode 100644 index 000000000..6920fffee --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/UtilExtensions.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar.DB2 +{ + /// + ///Common Extensions for external users + /// + public static class UtilExtensions + { + public static string ObjToStringNoTrim(this object thisValue) + { + if (thisValue != null) return thisValue.ToString(); + return ""; + } + public static string ToLower(this string value, bool isLower) + { + if (isLower) + { + return value.ObjToString().ToLower(); + } + return value.ObjToString(); + } + public static int ObjToInt(this object thisValue) + { + int reval = 0; + if (thisValue == null) return 0; + if (thisValue is Enum) + { + return (int)thisValue; + } + if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return reval; + } + + public static int ObjToInt(this object thisValue, int errorValue) + { + int reval = 0; + if (thisValue is Enum) + { + return (int)thisValue; + } + if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return errorValue; + } + + public static double ObjToMoney(this object thisValue) + { + double reval = 0; + if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return 0; + } + + public static double ObjToMoney(this object thisValue, double errorValue) + { + double reval = 0; + if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return errorValue; + } + + public static string ObjToString(this object thisValue) + { + if (thisValue != null) return thisValue.ToString().Trim(); + return ""; + } + + public static string ObjToString(this object thisValue, string errorValue) + { + if (thisValue != null) return thisValue.ToString().Trim(); + return errorValue; + } + + public static Decimal ObjToDecimal(this object thisValue) + { + Decimal reval = 0; + if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return 0; + } + + public static Decimal ObjToDecimal(this object thisValue, decimal errorValue) + { + Decimal reval = 0; + if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return errorValue; + } + + public static DateTime ObjToDate(this object thisValue) + { + DateTime reval = DateTime.MinValue; + if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval)) + { + reval = Convert.ToDateTime(thisValue); + } + return reval; + } + + public static DateTime ObjToDate(this object thisValue, DateTime errorValue) + { + DateTime reval = DateTime.MinValue; + if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return errorValue; + } + + public static bool ObjToBool(this object thisValue) + { + bool reval = false; + if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return reval; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/UtilMethods.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/UtilMethods.cs new file mode 100644 index 000000000..512d55519 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/UtilMethods.cs @@ -0,0 +1,507 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; + +namespace SqlSugar.DB2 +{ + public class UtilMethods + { + internal static DateTime GetMinDate(ConnectionConfig currentConnectionConfig) + { + if (currentConnectionConfig.MoreSettings == null) + { + return Convert.ToDateTime("1900-01-01"); + } + else if (currentConnectionConfig.MoreSettings.DbMinDate == null) + { + return Convert.ToDateTime("1900-01-01"); + } + else + { + return currentConnectionConfig.MoreSettings.DbMinDate.Value; + } + } + internal static DateTime ConvertFromDateTimeOffset(DateTimeOffset dateTime) + { + if (dateTime.Offset.Equals(TimeSpan.Zero)) + return dateTime.UtcDateTime; + else if (dateTime.Offset.Equals(TimeZoneInfo.Local.GetUtcOffset(dateTime.DateTime))) + return DateTime.SpecifyKind(dateTime.DateTime, DateTimeKind.Local); + else + return dateTime.DateTime; + } + + internal static object To(object value, Type destinationType) + { + return To(value, destinationType, CultureInfo.InvariantCulture); + } + + internal static object To(object value, Type destinationType, CultureInfo culture) + { + if (value != null) + { + destinationType = UtilMethods.GetUnderType(destinationType); + var sourceType = value.GetType(); + + var destinationConverter = TypeDescriptor.GetConverter(destinationType); + if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType())) + return destinationConverter.ConvertFrom(null, culture, value); + + var sourceConverter = TypeDescriptor.GetConverter(sourceType); + if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType)) + return sourceConverter.ConvertTo(null, culture, value, destinationType); + + if (destinationType.IsEnum && value is int) + return Enum.ToObject(destinationType, (int)value); + + if (!destinationType.IsInstanceOfType(value)) + return Convert.ChangeType(value, destinationType, culture); + } + return value; + } + public static bool IsAnyAsyncMethod(StackFrame[] methods) + { + bool isAsync = false; + foreach (var item in methods) + { + if (UtilMethods.IsAsyncMethod(item.GetMethod())) + { + isAsync = true; + break; + } + } + return isAsync; + } + + public static bool IsAsyncMethod(MethodBase method) + { + if (method == null) + { + return false; + } + if (method.DeclaringType != null) + { + if (method.DeclaringType.GetInterfaces().Contains(typeof(IAsyncStateMachine))) + { + return true; + } + } + var name = method.Name; + if (name.Contains("OutputAsyncCausalityEvents")) + { + return true; + } + if (name.Contains("OutputWaitEtwEvents")) + { + return true; + } + if (name.Contains("ExecuteAsync")) + { + return true; + } + Type attType = typeof(AsyncStateMachineAttribute); + var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType); + return (attrib != null); + } + + public static StackTraceInfo GetStackTrace() + { + + StackTrace st = new StackTrace(true); + StackTraceInfo info = new StackTraceInfo(); + info.MyStackTraceList = new List(); + info.SugarStackTraceList = new List(); + for (int i = 0; i < st.FrameCount; i++) + { + var frame = st.GetFrame(i); + if (frame.GetMethod().Module.Name.ToLower() != "sqlsugar.dll" && frame.GetMethod().Name.First() != '<') + { + info.MyStackTraceList.Add(new StackTraceInfoItem() + { + FileName = frame.GetFileName(), + MethodName = frame.GetMethod().Name, + Line = frame.GetFileLineNumber() + }); + } + else + { + info.SugarStackTraceList.Add(new StackTraceInfoItem() + { + FileName = frame.GetFileName(), + MethodName = frame.GetMethod().Name, + Line = frame.GetFileLineNumber() + }); + } + } + return info; + } + + internal static T To(object value) + { + return (T)To(value, typeof(T)); + } + internal static Type GetUnderType(Type oldType) + { + Type type = Nullable.GetUnderlyingType(oldType); + return type == null ? oldType : type; + } + public static string ReplaceSqlParameter(string itemSql, SugarParameter itemParameter, string newName) + { + itemSql = Regex.Replace(itemSql, string.Format(@"{0} ", "\\" + itemParameter.ParameterName), newName + " ", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"{0}\)", "\\" + itemParameter.ParameterName), newName + ")", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"{0}\,", "\\" + itemParameter.ParameterName), newName + ",", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"{0}$", "\\" + itemParameter.ParameterName), newName, RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"\+{0}\+", "\\" + itemParameter.ParameterName), "+" + newName + "+", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"\+{0} ", "\\" + itemParameter.ParameterName), "+" + newName + " ", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@" {0}\+", "\\" + itemParameter.ParameterName), " " + newName + "+", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"\|\|{0}\|\|", "\\" + itemParameter.ParameterName), "||" + newName + "||", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"\={0}\+", "\\" + itemParameter.ParameterName), "=" + newName + "+", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"{0}\|\|", "\\" + itemParameter.ParameterName), newName + "||", RegexOptions.IgnoreCase); + return itemSql; + } + internal static Type GetRootBaseType(Type entityType) + { + var baseType = entityType.BaseType; + while (baseType != null && baseType.BaseType != UtilConstants.ObjType) + { + baseType = baseType.BaseType; + } + return baseType; + } + + + internal static Type GetUnderType(PropertyInfo propertyInfo, ref bool isNullable) + { + Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType); + isNullable = unType != null; + unType = unType ?? propertyInfo.PropertyType; + return unType; + } + + internal static Type GetUnderType(PropertyInfo propertyInfo) + { + Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType); + unType = unType ?? propertyInfo.PropertyType; + return unType; + } + + internal static bool IsNullable(PropertyInfo propertyInfo) + { + Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType); + return unType != null; + } + + internal static bool IsNullable(Type type) + { + Type unType = Nullable.GetUnderlyingType(type); + return unType != null; + } + //internal static T IsNullReturnNew(T returnObj) where T : new() + //{ + // if (returnObj.IsNullOrEmpty()) + // { + // returnObj = new T(); + // } + // return returnObj; + //} + public static object ChangeType2(object value, Type type) + { + if (value == null && type.IsGenericType) return Activator.CreateInstance(type); + if (value == null) return null; + if (type == value.GetType()) return value; + if (type.IsEnum) + { + if (value is string) + return Enum.Parse(type, value as string); + else + return Enum.ToObject(type, value); + } + if (!type.IsInterface && type.IsGenericType) + { + Type innerType = type.GetGenericArguments()[0]; + object innerValue = ChangeType(value, innerType); + return Activator.CreateInstance(type, new object[] { innerValue }); + } + if (value is string && type == typeof(Guid)) return new Guid(value as string); + if (value is string && type == typeof(Version)) return new Version(value as string); + if (!(value is IConvertible)) return value; + return Convert.ChangeType(value, type); + } + + internal static T ChangeType(T obj, Type type) + { + return (T)Convert.ChangeType(obj, type); + } + + internal static T ChangeType(T obj) + { + return (T)Convert.ChangeType(obj, typeof(T)); + } + + internal static DateTimeOffset GetDateTimeOffsetByDateTime(DateTime date) + { + date = DateTime.SpecifyKind(date, DateTimeKind.Utc); + DateTimeOffset utcTime2 = date; + return utcTime2; + } + + //internal static void RepairReplicationParameters(ref string appendSql, SugarParameter[] parameters, int addIndex, string append = null) + //{ + // if (appendSql.HasValue() && parameters.HasValue()) + // { + // foreach (var parameter in parameters.OrderByDescending(it => it.ParameterName.Length)) + // { + // //Compatible with.NET CORE parameters case + // var name = parameter.ParameterName; + // string newName = name + append + addIndex; + // appendSql = ReplaceSqlParameter(appendSql, parameter, newName); + // parameter.ParameterName = newName; + // } + // } + //} + + internal static string GetPackTable(string sql, string shortName) + { + return string.Format(" ({0}) {1} ", sql, shortName); + } + + public static Func GetTypeConvert(object value) + { + if (value is int || value is uint || value is int? || value is uint?) + { + return x => Convert.ToInt32(x); + } + else if (value is short || value is ushort || value is short? || value is ushort?) + { + return x => Convert.ToInt16(x); + } + else if (value is long || value is long? || value is ulong? || value is long?) + { + return x => Convert.ToInt64(x); + } + else if (value is DateTime|| value is DateTime?) + { + return x => Convert.ToDateTime(x); + } + else if (value is bool||value is bool?) + { + return x => Convert.ToBoolean(x); + } + return null; + } + + internal static string GetTypeName(object value) + { + if (value == null) + { + return null; + } + else + { + return value.GetType().Name; + } + } + + internal static string GetParenthesesValue(string dbTypeName) + { + if (Regex.IsMatch(dbTypeName, @"\(.+\)")) + { + dbTypeName = Regex.Replace(dbTypeName, @"\(.+\)", ""); + } + dbTypeName = dbTypeName.Trim(); + return dbTypeName; + } + + internal static T GetOldValue(T value, Action action) + { + action(); + return value; + } + + internal static object DefaultForType(Type targetType) + { + return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; + } + + internal static Int64 GetLong(byte[] bytes) + { + return Convert.ToInt64(string.Join("", bytes).PadRight(20, '0')); + } + public static object GetPropertyValue(T t, string PropertyName) + { + return t.GetType().GetProperty(PropertyName).GetValue(t, null); + } + internal static string GetMD5(string myString) + { + MD5 md5 = new MD5CryptoServiceProvider(); + byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString); + byte[] targetData = md5.ComputeHash(fromData); + string byte2String = null; + + for (int i = 0; i < targetData.Length; i++) + { + byte2String += targetData[i].ToString("x"); + } + + return byte2String; + } + + //public static string EncodeBase64(string code) + //{ + // if (code.IsNullOrEmpty()) return code; + // string encode = ""; + // byte[] bytes = Encoding.GetEncoding("utf-8").GetBytes(code); + // try + // { + // encode = Convert.ToBase64String(bytes); + // } + // catch + // { + // encode = code; + // } + // return encode; + //} + public static string ConvertNumbersToString(string value) + { + string[] splitInt = value.Split(new char[] { '9' }, StringSplitOptions.RemoveEmptyEntries); + + var splitChars = splitInt.Select(s => Convert.ToChar( + Convert.ToInt32(s, 8) + ).ToString()); + + return string.Join("", splitChars); + } + public static string ConvertStringToNumbers(string value) + { + StringBuilder sb = new StringBuilder(); + + foreach (char c in value) + { + int cAscil = (int)c; + sb.Append(Convert.ToString(c, 8) + "9"); + } + + return sb.ToString(); + } + + //public static string DecodeBase64(string code) + //{ + // try + // { + // if (code.IsNullOrEmpty()) return code; + // string decode = ""; + // byte[] bytes = Convert.FromBase64String(code); + // try + // { + // decode = Encoding.GetEncoding("utf-8").GetString(bytes); + // } + // catch + // { + // decode = code; + // } + // return decode; + // } + // catch + // { + // return code; + // } + //} + + public static void DataInoveByExpresson(Type[] datas, MethodCallExpression callExpresion) + { + var methodInfo = callExpresion.Method; + foreach (var item in datas) + { + if (callExpresion.Arguments.Count == 0) + { + methodInfo.Invoke(item, null); + } + else + { + List methodParameters = new List(); + foreach (var callItem in callExpresion.Arguments) + { + var parameter = callItem.GetType().GetProperties().FirstOrDefault(it => it.Name == "Value"); + if (parameter == null) + { + var value = LambdaExpression.Lambda(callItem).Compile().DynamicInvoke(); + methodParameters.Add(value); + } + else + { + var value = parameter.GetValue(callItem, null); + methodParameters.Add(value); + } + } + methodInfo.Invoke(item, methodParameters.ToArray()); + } + } + } + + public static Dictionary EnumToDictionary() + { + Dictionary dic = new Dictionary(); + if (!typeof(T).IsEnum) + { + return dic; + } + string desc = string.Empty; + foreach (var item in Enum.GetValues(typeof(T))) + { + var key = item.ToString().ToLower(); + if (!dic.ContainsKey(key)) + dic.Add(key, (T)item); + } + return dic; + } + //public static object ConvertDataByTypeName(string ctypename,string value) + //{ + // var item = new ConditionalModel() { + // CSharpTypeName = ctypename, + // FieldValue = value + // }; + // if (item.CSharpTypeName.EqualCase(UtilConstants.DecType.Name)) + // { + // return Convert.ToDecimal(item.FieldValue); + // } + // else if (item.CSharpTypeName.EqualCase(UtilConstants.DobType.Name)) + // { + // return Convert.ToDouble(item.FieldValue); + // } + // else if (item.CSharpTypeName.EqualCase(UtilConstants.DateType.Name)) + // { + // return Convert.ToDateTime(item.FieldValue); + // } + // else if (item.CSharpTypeName.EqualCase(UtilConstants.IntType.Name)) + // { + // return Convert.ToInt32(item.FieldValue); + // } + // else if (item.CSharpTypeName.EqualCase(UtilConstants.LongType.Name)) + // { + // return Convert.ToInt64(item.FieldValue); + // } + // else if (item.CSharpTypeName.EqualCase(UtilConstants.ShortType.Name)) + // { + // return Convert.ToInt16(item.FieldValue); + // } + // else if (item.CSharpTypeName.EqualCase(UtilConstants.DateTimeOffsetType.Name)) + // { + // return UtilMethods.GetDateTimeOffsetByDateTime(Convert.ToDateTime(item.FieldValue)); + // } + // else + // { + // return item.FieldValue; + // } + //} + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/ValidateExtensions.cs b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/ValidateExtensions.cs new file mode 100644 index 000000000..4dc53176e --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.Db2Core/Tools/ValidateExtensions.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace SqlSugar.DB2 +{ + internal static class ValidateExtensions + { + public static bool IsInRange(this int thisValue, int begin, int end) + { + return thisValue >= begin && thisValue <= end; + } + + public static bool IsInRange(this DateTime thisValue, DateTime begin, DateTime end) + { + return thisValue >= begin && thisValue <= end; + } + + public static bool IsIn(this T thisValue, params T[] values) + { + return values.Contains(thisValue); + } + + public static bool IsContainsIn(this string thisValue, params string[] inValues) + { + return inValues.Any(it => thisValue.Contains(it)); + } + + public static bool IsNullOrEmpty(this object thisValue) + { + if (thisValue == null || thisValue == DBNull.Value) return true; + return thisValue.ToString() == ""; + } + + public static bool IsNullOrEmpty(this Guid? thisValue) + { + if (thisValue == null) return true; + return thisValue == Guid.Empty; + } + + public static bool IsNullOrEmpty(this Guid thisValue) + { + if (thisValue == null) return true; + return thisValue == Guid.Empty; + } + + public static bool IsNullOrEmpty(this IEnumerable thisValue) + { + if (thisValue == null || thisValue.Count() == 0) return true; + return false; + } + + public static bool HasValue(this object thisValue) + { + if (thisValue == null || thisValue == DBNull.Value) return false; + return thisValue.ToString() != ""; + } + + public static bool HasValue(this IEnumerable thisValue) + { + if (thisValue == null || thisValue.Count() == 0) return false; + return true; + } + + public static bool IsValuable(this IEnumerable> thisValue) + { + if (thisValue == null || thisValue.Count() == 0) return false; + return true; + } + + public static bool IsZero(this object thisValue) + { + return (thisValue == null || thisValue.ToString() == "0"); + } + + public static bool IsInt(this object thisValue) + { + if (thisValue == null) return false; + return Regex.IsMatch(thisValue.ToString(), @"^\d+$"); + } + + /// + public static bool IsNoInt(this object thisValue) + { + if (thisValue == null) return true; + return !Regex.IsMatch(thisValue.ToString(), @"^\d+$"); + } + + public static bool IsMoney(this object thisValue) + { + if (thisValue == null) return false; + double outValue = 0; + return double.TryParse(thisValue.ToString(), out outValue); + } + public static bool IsGuid(this object thisValue) + { + if (thisValue == null) return false; + Guid outValue = Guid.Empty; + return Guid.TryParse(thisValue.ToString(), out outValue); + } + + public static bool IsDate(this object thisValue) + { + if (thisValue == null) return false; + DateTime outValue = DateTime.MinValue; + return DateTime.TryParse(thisValue.ToString(), out outValue); + } + + public static bool IsEamil(this object thisValue) + { + if (thisValue == null) return false; + return Regex.IsMatch(thisValue.ToString(), @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$"); + } + + public static bool IsMobile(this object thisValue) + { + if (thisValue == null) return false; + return Regex.IsMatch(thisValue.ToString(), @"^\d{11}$"); + } + + public static bool IsTelephone(this object thisValue) + { + if (thisValue == null) return false; + return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{8}$"); + + } + + public static bool IsIDcard(this object thisValue) + { + if (thisValue == null) return false; + return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$"); + } + + public static bool IsFax(this object thisValue) + { + if (thisValue == null) return false; + return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$"); + } + + public static bool IsMatch(this object thisValue, string pattern) + { + if (thisValue == null) return false; + Regex reg = new Regex(pattern); + return reg.IsMatch(thisValue.ToString()); + } + public static bool IsAnonymousType(this Type type) + { + string typeName = type.Name; + return typeName.Contains("<>") && typeName.Contains("__") && typeName.Contains("AnonymousType"); + } + public static bool IsCollectionsList(this string thisValue) + { + return (thisValue + "").StartsWith("System.Collections.Generic.List")|| (thisValue + "").StartsWith("System.Collections.Generic.IEnumerable"); + } + public static bool IsStringArray(this string thisValue) + { + return (thisValue + "").IsMatch(@"System\.[a-z,A-Z,0-9]+?\[\]"); + } + public static bool IsEnumerable(this string thisValue) + { + return (thisValue + "").StartsWith("System.Linq.Enumerable"); + } + + public static Type StringType = typeof (string); + + public static bool IsClass(this Type thisValue) + { + return thisValue != StringType && thisValue.IsEntity()&&thisValue!=UtilConstants.ByteArrayType; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugarCore.sln b/Src/Asp.NetCore2/SqlSugarCore.sln index 4b4cdb8ac..d731ffc15 100644 --- a/Src/Asp.NetCore2/SqlSugarCore.sln +++ b/Src/Asp.NetCore2/SqlSugarCore.sln @@ -86,6 +86,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SqlSugar.HANAConnector", "S EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HANATest", "HANATest\HANATest.csproj", "{B6E4F79F-1B62-413C-94B5-EDBF6CD71432}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DB2CoreTest", "DB2CoreTest\DB2CoreTest.csproj", "{72CDC782-42CB-9D3B-2FA6-0BEFF499A984}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SqlSugar.Db2Core", "SqlSugar.Db2Core\SqlSugar.Db2Core.csproj", "{F706204F-2FC4-5112-646F-28D498E56AF4}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -552,6 +556,30 @@ Global {B6E4F79F-1B62-413C-94B5-EDBF6CD71432}.Release|ARM32.Build.0 = Release|Any CPU {B6E4F79F-1B62-413C-94B5-EDBF6CD71432}.Release|x86.ActiveCfg = Release|Any CPU {B6E4F79F-1B62-413C-94B5-EDBF6CD71432}.Release|x86.Build.0 = Release|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Debug|Any CPU.Build.0 = Debug|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Debug|ARM32.ActiveCfg = Debug|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Debug|ARM32.Build.0 = Debug|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Debug|x86.ActiveCfg = Debug|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Debug|x86.Build.0 = Debug|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Release|Any CPU.ActiveCfg = Release|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Release|Any CPU.Build.0 = Release|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Release|ARM32.ActiveCfg = Release|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Release|ARM32.Build.0 = Release|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Release|x86.ActiveCfg = Release|Any CPU + {72CDC782-42CB-9D3B-2FA6-0BEFF499A984}.Release|x86.Build.0 = Release|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Debug|ARM32.ActiveCfg = Debug|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Debug|ARM32.Build.0 = Debug|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Debug|x86.ActiveCfg = Debug|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Debug|x86.Build.0 = Debug|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Release|Any CPU.Build.0 = Release|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Release|ARM32.ActiveCfg = Release|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Release|ARM32.Build.0 = Release|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Release|x86.ActiveCfg = Release|Any CPU + {F706204F-2FC4-5112-646F-28D498E56AF4}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -568,6 +596,7 @@ Global {86C30210-A729-4F66-958D-173ADC512B2B} = {88992AAF-146B-4253-9AD7-493E8F415B57} {B86EC97E-13F2-422B-8CA0-46181D40DEF2} = {88992AAF-146B-4253-9AD7-493E8F415B57} {B3C4B993-C33E-48AF-955F-EB801774FBE8} = {88992AAF-146B-4253-9AD7-493E8F415B57} + {F706204F-2FC4-5112-646F-28D498E56AF4} = {88992AAF-146B-4253-9AD7-493E8F415B57} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {230A85B9-54F1-41B1-B1DA-80086581B2B4}