From 9c12cfc28b0ca7ed192749e7026b6108c60b8994 Mon Sep 17 00:00:00 2001 From: sunkaixuna <610262374@qq.com> Date: Sun, 6 Feb 2022 16:08:31 +0800 Subject: [PATCH] Update core --- .../SqlSeverTest/SqlSeverTest.sln | 13 +- .../DataTableExtensions/MySqlDataAdapter.cs | 156 ++++++ .../MySql/CodeFirst/MySqlCodeFirst.cs | 80 +++ .../MySql/DbBind/MySqlDbBind.cs | 97 ++++ .../MySql/DbFirst/MySqlDbFirst.cs | 11 + .../MySql/DbMaintenance/MySqlDbMaintenance.cs | 464 +++++++++++++++++ .../MySql/MySqlProvider.cs | 310 +++++++++++ .../MySql/Queryable/MySqlQueryable.cs | 60 +++ .../MySql/SqlBuilder/MySqlBlukCopy.cs | 202 +++++++ .../MySql/SqlBuilder/MySqlBuilder.cs | 26 + .../MySql/SqlBuilder/MySqlDeleteBuilder.cs | 7 + .../SqlBuilder/MySqlExpressionContext.cs | 154 ++++++ .../MySql/SqlBuilder/MySqlFastBuilder.cs | 74 +++ .../MySql/SqlBuilder/MySqlInsertBuilder.cs | 136 +++++ .../MySql/SqlBuilder/MySqlQueryBuilder.cs | 138 +++++ .../MySql/SqlBuilder/MySqlUpdateBuilder.cs | 155 ++++++ .../SqlSugar.MySqlConnectorCore.csproj | 15 + .../Tools/ErrorMessage.cs | 64 +++ .../Tools/FileHelper.cs | 70 +++ .../Tools/UtilConstants.cs | 73 +++ .../Tools/UtilExtensions.cs | 123 +++++ .../Tools/UtilMethods.cs | 493 ++++++++++++++++++ .../Tools/ValidateExtensions.cs | 172 ++++++ .../Abstract/AdoProvider/AdoProvider.cs | 16 +- .../Abstract/FastestProvider/Private.cs | 4 +- .../SugarProvider/SqlSugarAccessory.cs | 10 + .../UpdateProvider/UpdateableProvider.cs | 4 +- .../SqlSugar/Entities/ConnMoreSettings.cs | 1 + .../SqlSeverTest/SqlSugar/Enum/DbType.cs | 5 +- .../MethodCallExpressionResolve.cs | 8 +- .../Infrastructure/InstanceFactory.cs | 76 ++- 31 files changed, 3197 insertions(+), 20 deletions(-) create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/DataTableExtensions/MySqlDataAdapter.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/CodeFirst/MySqlCodeFirst.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbBind/MySqlDbBind.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbFirst/MySqlDbFirst.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbMaintenance/MySqlDbMaintenance.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/MySqlProvider.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/Queryable/MySqlQueryable.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlBlukCopy.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlBuilder.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlDeleteBuilder.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlExpressionContext.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlFastBuilder.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlInsertBuilder.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlQueryBuilder.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlUpdateBuilder.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/SqlSugar.MySqlConnectorCore.csproj create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/ErrorMessage.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/FileHelper.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilConstants.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilExtensions.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilMethods.cs create mode 100644 Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/ValidateExtensions.cs diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln b/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln index 5ce526877..51a60b16d 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln @@ -25,7 +25,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CacheTest", "CacheTest\Cach EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OscarTest", "OscarTest\OscarTest.csproj", "{29925F8E-6495-463A-ABBD-C050AE85E130}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbFirstRazorTest", "DbFirstRazorTest\DbFirstRazorTest.csproj", "{EE197EB0-C494-4478-A5CD-545E7139202E}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbFirstRazorTest", "DbFirstRazorTest\DbFirstRazorTest.csproj", "{EE197EB0-C494-4478-A5CD-545E7139202E}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SqlSugar.CustomDatabase", "SqlSugar.CustomDatabase", "{88992AAF-146B-4253-9AD7-493E8F415B57}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SqlSugar.MySqlConnectorCore", "SqlSugar.MySqlConnectorCore\SqlSugar.MySqlConnectorCore.csproj", "{D22873F3-80E1-4415-9CD6-21B1C7EEA4A0}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -81,10 +85,17 @@ Global {EE197EB0-C494-4478-A5CD-545E7139202E}.Debug|Any CPU.Build.0 = Debug|Any CPU {EE197EB0-C494-4478-A5CD-545E7139202E}.Release|Any CPU.ActiveCfg = Release|Any CPU {EE197EB0-C494-4478-A5CD-545E7139202E}.Release|Any CPU.Build.0 = Release|Any CPU + {D22873F3-80E1-4415-9CD6-21B1C7EEA4A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D22873F3-80E1-4415-9CD6-21B1C7EEA4A0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D22873F3-80E1-4415-9CD6-21B1C7EEA4A0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D22873F3-80E1-4415-9CD6-21B1C7EEA4A0}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {D22873F3-80E1-4415-9CD6-21B1C7EEA4A0} = {88992AAF-146B-4253-9AD7-493E8F415B57} + EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {230A85B9-54F1-41B1-B1DA-80086581B2B4} EndGlobalSection diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/DataTableExtensions/MySqlDataAdapter.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/DataTableExtensions/MySqlDataAdapter.cs new file mode 100644 index 000000000..b8af8dfa9 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/DataTableExtensions/MySqlDataAdapter.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Text; +using MySqlConnector; + +namespace SqlSugar.MySqlConnectorCore +{ + /// + /// 数据填充器 + /// + public class MySqlConnectorDataAdapter : IDataAdapter + { + private MySqlCommand command; + private string sql; + private MySqlConnection _sqlConnection; + + /// + /// SqlDataAdapter + /// + /// + public MySqlConnectorDataAdapter(MySqlCommand command) + { + this.command = command; + } + + public MySqlConnectorDataAdapter() + { + + } + + /// + /// SqlDataAdapter + /// + /// + /// + public MySqlConnectorDataAdapter(string sql, MySqlConnection _sqlConnection) + { + this.sql = sql; + this._sqlConnection = _sqlConnection; + } + + /// + /// SelectCommand + /// + public MySqlCommand SelectCommand + { + get + { + if (this.command == null) + { + this.command = new MySqlCommand(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 (MySqlDataReader 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 (MySqlDataReader 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 (dr.GetFieldType(i).Name == "MySqlDateTime") + { + if (!columns.Contains(name)) + columns.Add(new DataColumn(name, UtilConstants.DateType)); + else + { + columns.Add(new DataColumn(name + i, UtilConstants.DateType)); + } + } + else + { + 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/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/CodeFirst/MySqlCodeFirst.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/CodeFirst/MySqlCodeFirst.cs new file mode 100644 index 000000000..11f711fb0 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/CodeFirst/MySqlCodeFirst.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlCodeFirst : CodeFirstProvider + { + 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.OrderBy(it => it.IsPrimarykey ? 0 : 1)) + { + if (item.IsIgnore) + continue; + if (item.PropertyInfo!=null&&UtilMethods.GetUnderType(item.PropertyInfo.PropertyType) == UtilConstants.GuidType && item.Length == 0&&item.DataType==null) + { + item.Length = Guid.NewGuid().ToString().Length; + } + DbColumnInfo dbColumnInfo = this.EntityColumnToDbColumn(entityInfo, tableName, item); + columns.Add(dbColumnInfo); + } + } + 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, + 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); + } + + internal DbColumnInfo GetEntityColumnToDbColumn(EntityInfo entity, string dbTableName, EntityColumnInfo item) + { + return EntityColumnToDbColumn(entity,dbTableName,item); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbBind/MySqlDbBind.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbBind/MySqlDbBind.cs new file mode 100644 index 000000000..13193a382 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbBind/MySqlDbBind.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlDbBind : DbBindProvider + { + public override string GetDbTypeName(string csharpTypeName) + { + if (csharpTypeName == UtilConstants.ByteArrayType.Name) + { + return "blob"; + } + if (csharpTypeName == "Int32") + csharpTypeName = "int"; + if (csharpTypeName == "Int16") + csharpTypeName = "short"; + if (csharpTypeName == "Int64") + csharpTypeName = "long"; + if (csharpTypeName == "Boolean") + csharpTypeName = "bool"; + if (csharpTypeName == "SByte") + csharpTypeName = "Byte"; + if (csharpTypeName == "DateTimeOffset") + csharpTypeName = "DateTime"; + var mappings = this.MappingTypes.Where(it => it.Value.ToString().Equals(csharpTypeName, StringComparison.CurrentCultureIgnoreCase)); + return mappings.HasValue() ? mappings.First().Key : "varchar"; + } + 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("int",CSharpDataType.@int), + new KeyValuePair("mediumint",CSharpDataType.@int), + new KeyValuePair("integer",CSharpDataType.@int), + + new KeyValuePair("varchar",CSharpDataType.@string), + new KeyValuePair("text",CSharpDataType.@string), + new KeyValuePair("char",CSharpDataType.@string), + new KeyValuePair("enum",CSharpDataType.@string), + new KeyValuePair("mediumtext",CSharpDataType.@string), + new KeyValuePair("tinytext",CSharpDataType.@string), + new KeyValuePair("longtext",CSharpDataType.@string), + + new KeyValuePair("tinyint",CSharpDataType.@byte), + new KeyValuePair("smallint",CSharpDataType.@short), + new KeyValuePair("bigint",CSharpDataType.@long), + new KeyValuePair("bit",CSharpDataType.@bool), + new KeyValuePair("real",CSharpDataType.@double), + new KeyValuePair("double",CSharpDataType.@double), + new KeyValuePair("float",CSharpDataType.@float), + new KeyValuePair("float",CSharpDataType.Single), + new KeyValuePair("decimal",CSharpDataType.@decimal), + new KeyValuePair("numeric",CSharpDataType.@decimal), + new KeyValuePair("year",CSharpDataType.@int), + + new KeyValuePair("datetime",CSharpDataType.DateTime), + new KeyValuePair("timestamp",CSharpDataType.DateTime), + new KeyValuePair("date",CSharpDataType.DateTime), + new KeyValuePair("time",CSharpDataType.DateTime), + + new KeyValuePair("blob",CSharpDataType.byteArray), + new KeyValuePair("longblob",CSharpDataType.byteArray), + new KeyValuePair("tinyblob",CSharpDataType.byteArray), + new KeyValuePair("varbinary",CSharpDataType.byteArray), + new KeyValuePair("binary",CSharpDataType.byteArray), + new KeyValuePair("multipoint",CSharpDataType.byteArray), + new KeyValuePair("geometry",CSharpDataType.byteArray), + new KeyValuePair("multilinestring",CSharpDataType.byteArray), + new KeyValuePair("polygon",CSharpDataType.byteArray), + new KeyValuePair("mediumblob",CSharpDataType.byteArray), + + new KeyValuePair("varchar",CSharpDataType.Guid), + }; + public override List StringThrow + { + get + { + return new List() { "int32", "datetime", "decimal", "double", "byte" }; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbFirst/MySqlDbFirst.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbFirst/MySqlDbFirst.cs new file mode 100644 index 000000000..7d86e1a22 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbFirst/MySqlDbFirst.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlDbFirst : DbFirstProvider + { + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbMaintenance/MySqlDbMaintenance.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbMaintenance/MySqlDbMaintenance.cs new file mode 100644 index 000000000..b8a1ebf35 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/DbMaintenance/MySqlDbMaintenance.cs @@ -0,0 +1,464 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlDbMaintenance : DbMaintenanceProvider + { + #region DML + protected override string GetDataBaseSql + { + get + { + return "SHOW DATABASES"; + } + } + protected override string GetColumnInfosByTableNameSql + { + get + { + string sql = @"SELECT + 0 as TableId, + TABLE_NAME as TableName, + column_name AS DbColumnName, + CASE WHEN left(COLUMN_TYPE,LOCATE('(',COLUMN_TYPE)-1)='' THEN COLUMN_TYPE ELSE left(COLUMN_TYPE,LOCATE('(',COLUMN_TYPE)-1) END AS DataType, + CAST(SUBSTRING(COLUMN_TYPE,LOCATE('(',COLUMN_TYPE)+1,LOCATE(')',COLUMN_TYPE)-LOCATE('(',COLUMN_TYPE)-1) AS signed) AS Length, + column_default AS `DefaultValue`, + column_comment AS `ColumnDescription`, + CASE WHEN COLUMN_KEY = 'PRI' + THEN true ELSE false END AS `IsPrimaryKey`, + CASE WHEN EXTRA='auto_increment' THEN true ELSE false END as IsIdentity, + CASE WHEN is_nullable = 'YES' + THEN true ELSE false END AS `IsNullable`, + numeric_scale as Scale, + numeric_scale as DecimalDigits + FROM + Information_schema.columns where TABLE_NAME='{0}' and TABLE_SCHEMA=(select database()) ORDER BY ordinal_position"; + return sql; + } + } + protected override string GetTableInfoListSql + { + get + { + return @"select TABLE_NAME as Name,TABLE_COMMENT as Description from information_schema.tables + where TABLE_SCHEMA=(select database()) AND TABLE_TYPE='BASE TABLE'"; + } + } + protected override string GetViewInfoListSql + { + get + { + return @"select TABLE_NAME as Name,TABLE_COMMENT as Description from information_schema.tables + where TABLE_SCHEMA=(select database()) AND TABLE_TYPE='VIEW' + "; + } + } + #endregion + + #region DDL + protected override string CreateDataBaseSql + { + get + { + return "CREATE DATABASE `{0}` CHARACTER SET utf8 COLLATE utf8_general_ci "; + } + } + protected override string AddPrimaryKeySql + { + get + { + return "ALTER TABLE {0} ADD PRIMARY KEY({2}) /*{1}*/"; + } + } + protected override string AddColumnToTableSql + { + get + { + return "ALTER TABLE {0} ADD {1} {2}{3} {4} {5} {6}"; + } + } + protected override string AlterColumnToTableSql + { + get + { + // return "ALTER TABLE {0} ALTER COLUMN {1} {2}{3} {4} {5} {6}"; + return "alter table {0} change column {1} {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} $PrimaryKey)"; + } + } + 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 {1} (Select * from {2} LIMIT 0,{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 primary key;"; + } + } + protected override string RenameColumnSql + { + get + { + return "alter table {0} change column {1} {2}"; + } + } + #endregion + + #region Check + protected override string CheckSystemTablePermissionsSql + { + get + { + return "select 1 from Information_schema.columns limit 0,1"; + } + } + #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 "AUTO_INCREMENT"; + } + } + + protected override string AddColumnRemarkSql + { + get + { + throw new NotSupportedException(); + } + } + + protected override string DeleteColumnRemarkSql + { + get + { + throw new NotSupportedException(); + } + } + + protected override string IsAnyColumnRemarkSql + { + get + { + throw new NotSupportedException(); + } + } + + protected override string AddTableRemarkSql + { + get + { + return "ALTER TABLE {0} COMMENT='{1}';"; + } + } + + protected override string DeleteTableRemarkSql + { + get + { + return "ALTER TABLE {0} COMMENT='';"; + } + } + + protected override string IsAnyTableRemarkSql + { + get + { + throw new NotSupportedException(); + } + } + + protected override string RenameTableSql { + get + { + return "alter table {0} rename {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(*) FROM information_schema.statistics WHERE index_name = '{0}'"; + } + } + #endregion + + #region Methods + /// + ///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; + Check.Exception(Regex.Split(connection,oldDatabaseName).Length > 2, "The user name and password cannot be the same as the database name "); + connection = connection.Replace(oldDatabaseName, "mysql"); + var newDb = new SqlSugarClient(new ConnectionConfig() + { + DbType = this.Context.CurrentConnectionConfig.DbType, + IsAutoCloseConnection = true, + ConnectionString = connection + }); + if (!GetDataBaseList(newDb).Any(it => it.Equals(databaseName, StringComparison.CurrentCultureIgnoreCase))) + { + newDb.Ado.ExecuteCommand(string.Format(CreateDataBaseSql, databaseName, databaseDirectory)); + } + return true; + } + public override bool AddTableRemark(string tableName, string description) + { + string sql = string.Format(this.AddTableRemarkSql, this.SqlBuilder.GetTranslationTableName(tableName), description); + this.Context.Ado.ExecuteCommand(sql); + 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); + string primaryKeyInfo = null; + if (columns.Any(it => it.IsPrimarykey)&&isCreatePrimaryKey) { + primaryKeyInfo =string.Format( ", Primary key({0})",string.Join(",",columns.Where(it=>it.IsPrimarykey).Select(it=>this.SqlBuilder.GetTranslationColumnName(it.DbColumnName)))); + + } + sql = sql.Replace("$PrimaryKey", primaryKeyInfo); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + public override bool AddRemark(EntityInfo entity) + { + var db = this.Context; + db.DbMaintenance.AddTableRemark(entity.DbTableName, entity.TableDescription); + List columns = entity.Columns.Where(it => it.IsIgnore == false).ToList(); + foreach (var item in columns) + { + if (item.ColumnDescription != null) + { + var mySqlCodeFirst = this.Context.CodeFirst as MySqlCodeFirst; + string sql = GetUpdateColumnSql(entity.DbTableName, mySqlCodeFirst.GetEntityColumnToDbColumn(entity, entity.DbTableName, item))+" "+(item.IsIdentity? "AUTO_INCREMENT" : "")+" " + " COMMENT '" + item.ColumnDescription + "'"; + db.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 dataSize = ""; + dataSize = GetSize(item); + string dataType = item.DataType; + string nullType = item.IsNullable ? this.CreateTableNull : CreateTableNotNull; + string primaryKey = null; + string identity = item.IsIdentity ? this.CreateTableIdentity : null; + string addItem = string.Format(this.CreateTableColumn, this.SqlBuilder.GetTranslationColumnName(columnName), dataType, dataSize, nullType, primaryKey, identity); + columnArray.Add(addItem); + } + string tableString = string.Format(this.CreateTableSql, this.SqlBuilder.GetTranslationTableName(tableName), string.Join(",\r\n", columnArray)); + return tableString; + } + + protected override string GetSize(DbColumnInfo item) + { + string dataSize = null; + var isMax = item.Length > 4000 || item.Length == -1; + if (isMax) + { + dataSize=""; + item.DataType = "longtext"; + } + else if (item.Length > 0 && item.DecimalDigits == 0) + { + dataSize = item.Length > 0 ? string.Format("({0})", item.Length) : null; + } + else if (item.Length == 0 && item.DecimalDigits > 0) + { + item.Length = 10; + dataSize = string.Format("({0},{1})", item.Length, item.DecimalDigits); + } + else if (item.Length > 0 && item.DecimalDigits > 0) + { + dataSize = item.Length > 0 ? string.Format("({0},{1})", item.Length, item.DecimalDigits) : null; + } + return dataSize; + } + + public override bool RenameColumn(string tableName, string oldColumnName, string newColumnName) + { + var columns=GetColumnInfosByTableName(tableName).Where(it=>it.DbColumnName.Equals(oldColumnName,StringComparison.CurrentCultureIgnoreCase)); + if (columns != null && columns.Any()) + { + var column = columns.First(); + var appendSql = " " + column.DataType; + if (column.Length > 0 && column.Scale == 0) + { + appendSql += string.Format("({0}) ", column.Length); + } + else if (column.Scale > 0 && column.Length > 0) + { + appendSql += string.Format("({0},{1}) ", column.Length, column.Scale); + } + else + { + appendSql += column.IsNullable ? " NULL " : " NOT NULL "; + } + tableName = this.SqlBuilder.GetTranslationTableName(tableName); + oldColumnName = this.SqlBuilder.GetTranslationColumnName(oldColumnName); + newColumnName = this.SqlBuilder.GetTranslationColumnName(newColumnName); + string sql = string.Format(this.RenameColumnSql, tableName, oldColumnName, newColumnName+appendSql); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + else + { + return false; + } + } + public override bool AddDefaultValue(string tableName, string columnName, string defaultValue) + { + if (defaultValue == "''") + { + defaultValue = ""; + } + if (defaultValue.ToLower().IsIn("now()", "current_timestamp")|| defaultValue.ToLower().Contains("current_timestamp")) + { + string template = "ALTER table {0} CHANGE COLUMN {1} {1} {3} default {2}"; + var dbColumnInfo = this.Context.DbMaintenance.GetColumnInfosByTableName(tableName).First(it => it.DbColumnName.Equals(columnName, StringComparison.CurrentCultureIgnoreCase)); + string sql = string.Format(template, tableName, columnName, defaultValue, dbColumnInfo.DataType); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + else if (defaultValue=="0"|| defaultValue == "1") + { + string sql = string.Format(AddDefaultValueSql.Replace("'",""), tableName, columnName, defaultValue); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + else + { + return base.AddDefaultValue(tableName, columnName, defaultValue); + } + } + public override bool IsAnyConstraint(string constraintName) + { + throw new NotSupportedException("MySql IsAnyConstraint NotSupportedException"); + } + public override bool BackupDataBase(string databaseName, string fullFileName) + { + Check.ThrowNotSupportedException("MySql BackupDataBase NotSupported"); + return false; + } + + #endregion + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/MySqlProvider.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/MySqlProvider.cs new file mode 100644 index 000000000..29964feb5 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/MySqlProvider.cs @@ -0,0 +1,310 @@ +using MySqlConnector; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlProvider : AdoProvider + { + public MySqlProvider() { } + public override IDbConnection Connection + { + get + { + if (base._DbConnection == null) + { + try + { + var mySqlConnectionString = base.Context.CurrentConnectionConfig.ConnectionString; + if (!mySqlConnectionString.ToLower().Contains("charset")) + { + mySqlConnectionString = mySqlConnectionString.Trim().TrimEnd(';') + ";charset=utf8;"; + } + base._DbConnection = new MySqlConnection(mySqlConnectionString); + } + catch (Exception ex) + { + Check.Exception(true, ex.Message); + } + } + 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 MySqlDataAdapter(); + } + public override DbCommand GetCommand(string sql, SugarParameter[] parameters) + { + MySqlCommand sqlCommand = new MySqlCommand(sql, (MySqlConnection)this.Connection); + sqlCommand.CommandType = this.CommandType; + sqlCommand.CommandTimeout = this.CommandTimeOut; + if (this.Transaction != null) + { + sqlCommand.Transaction = (MySqlTransaction)this.Transaction; + } + if (parameters.HasValue()) + { + IDataParameter[] ipars = ToIDbDataParameter(parameters); + sqlCommand.Parameters.AddRange((MySqlParameter[])ipars); + } + CheckConnection(); + return sqlCommand; + } + public override void SetCommandToAdapter(IDataAdapter dataAdapter, DbCommand command) + { + ((MySqlConnectorDataAdapter)dataAdapter).SelectCommand = (MySqlCommand)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; + MySqlParameter[] result = new MySqlParameter[parameters.Length]; + int index = 0; + var isVarchar =IsVarchar(); + foreach (var parameter in parameters) + { + if (parameter.Value == null) parameter.Value = DBNull.Value; + var sqlParameter = new MySqlParameter(); + sqlParameter.ParameterName = parameter.ParameterName; + sqlParameter.Size = parameter.Size; + sqlParameter.Value = parameter.Value; + sqlParameter.DbType = parameter.DbType; + if (parameter.Direction == 0) + { + parameter.Direction = ParameterDirection.Input; + } + sqlParameter.Direction = parameter.Direction; + //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 (parameter.DbType== System.Data.DbType.DateTimeOffset) + { + if(sqlParameter.Value != DBNull.Value) + sqlParameter.Value = UtilMethods.ConvertFromDateTimeOffset((DateTimeOffset)sqlParameter.Value); + sqlParameter.DbType = System.Data.DbType.DateTime; + } + ++index; + } + return result; + } + + private bool IsVarchar() + { + if (this.Context.CurrentConnectionConfig.MoreSettings != null && this.Context.CurrentConnectionConfig.MoreSettings.DisableNvarchar) + { + return true; + } + return false; + } + + + #region async + public async Task CloseAsync() + { + if (this.Transaction != null) + { + this.Transaction = null; + } + if (this.Connection != null && this.Connection.State == ConnectionState.Open) + { + await (this.Connection as MySqlConnection).CloseAsync(); + } + if (this.IsMasterSlaveSeparation && this.SlaveConnections.HasValue()) + { + foreach (var slaveConnection in this.SlaveConnections) + { + if (slaveConnection != null && slaveConnection.State == ConnectionState.Open) + { + await (slaveConnection as MySqlConnection).CloseAsync(); + } + } + } + } + public async Task GetCommandAsync(string sql, SugarParameter[] parameters) + { + MySqlCommand sqlCommand = new MySqlCommand(sql, (MySqlConnection)this.Connection); + sqlCommand.CommandType = this.CommandType; + sqlCommand.CommandTimeout = this.CommandTimeOut; + if (this.Transaction != null) + { + sqlCommand.Transaction = (MySqlTransaction)this.Transaction; + } + if (parameters.HasValue()) + { + IDataParameter[] ipars = ToIDbDataParameter(parameters); + sqlCommand.Parameters.AddRange((MySqlParameter[])ipars); + } + if (this.Connection.State != ConnectionState.Open) + { + try + { + await (this.Connection as MySqlConnection).OpenAsync(); + } + catch (Exception ex) + { + Check.Exception(true, ex.Message); + } + } + return sqlCommand; + } + public override async Task ExecuteCommandAsync(string sql, params SugarParameter[] parameters) + { + try + { + Async(); + InitParameters(ref sql, parameters); + if (FormatSql != null) + sql = FormatSql(sql); + SetConnectionStart(sql); + if (this.ProcessingEventStartingSQL != null) + ExecuteProcessingSQL(ref sql, parameters); + ExecuteBefore(sql, parameters); + var sqlCommand =await GetCommandAsync(sql, parameters); + int count; + if (this.CancellationToken == null) + count = await sqlCommand.ExecuteNonQueryAsync(); + else + count = await sqlCommand.ExecuteNonQueryAsync(this.CancellationToken.Value); + if (this.IsClearParameters) + sqlCommand.Parameters.Clear(); + ExecuteAfter(sql, parameters); + sqlCommand.Dispose(); + return count; + } + catch (Exception ex) + { + CommandType = CommandType.Text; + if (ErrorEvent != null) + ExecuteErrorEvent(sql, parameters, ex); + throw ex; + } + finally + { + if (this.IsAutoClose()) + { + await this.CloseAsync(); + } + SetConnectionEnd(sql); + } + } + public override async Task GetDataReaderAsync(string sql, params SugarParameter[] parameters) + { + try + { + Async(); + InitParameters(ref sql, parameters); + if (FormatSql != null) + sql = FormatSql(sql); + SetConnectionStart(sql); + var isSp = this.CommandType == CommandType.StoredProcedure; + if (this.ProcessingEventStartingSQL != null) + ExecuteProcessingSQL(ref sql, parameters); + ExecuteBefore(sql, parameters); + var sqlCommand = await GetCommandAsync(sql, parameters); + DbDataReader sqlDataReader; + if (this.CancellationToken == null) + sqlDataReader = await sqlCommand.ExecuteReaderAsync(this.IsAutoClose() ? CommandBehavior.CloseConnection : CommandBehavior.Default); + else + sqlDataReader = await sqlCommand.ExecuteReaderAsync(this.IsAutoClose() ? CommandBehavior.CloseConnection : CommandBehavior.Default, this.CancellationToken.Value); + if (isSp) + DataReaderParameters = sqlCommand.Parameters; + if (this.IsClearParameters) + sqlCommand.Parameters.Clear(); + ExecuteAfter(sql, parameters); + SetConnectionEnd(sql); + if (SugarCompatible.IsFramework || this.Context.CurrentConnectionConfig.DbType != DbType.Sqlite) + sqlCommand.Dispose(); + return sqlDataReader; + } + catch (Exception ex) + { + CommandType = CommandType.Text; + if (ErrorEvent != null) + ExecuteErrorEvent(sql, parameters, ex); + throw ex; + } + } + public override async Task GetScalarAsync(string sql, params SugarParameter[] parameters) + { + try + { + Async(); + InitParameters(ref sql, parameters); + if (FormatSql != null) + sql = FormatSql(sql); + SetConnectionStart(sql); + if (this.ProcessingEventStartingSQL != null) + ExecuteProcessingSQL(ref sql, parameters); + ExecuteBefore(sql, parameters); + var sqlCommand = await GetCommandAsync(sql, parameters) ; + object scalar; + if (CancellationToken == null) + scalar = await sqlCommand.ExecuteScalarAsync(); + else + scalar = await sqlCommand.ExecuteScalarAsync(this.CancellationToken.Value); + //scalar = (scalar == null ? 0 : scalar); + if (this.IsClearParameters) + sqlCommand.Parameters.Clear(); + ExecuteAfter(sql, parameters); + sqlCommand.Dispose(); + return scalar; + } + catch (Exception ex) + { + CommandType = CommandType.Text; + if (ErrorEvent != null) + ExecuteErrorEvent(sql, parameters, ex); + throw ex; + } + finally + { + if (this.IsAutoClose()) + { + await this.CloseAsync(); + } + SetConnectionEnd(sql); + } + } + #endregion + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/Queryable/MySqlQueryable.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/Queryable/MySqlQueryable.cs new file mode 100644 index 000000000..3eaa2dacc --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/Queryable/MySqlQueryable.cs @@ -0,0 +1,60 @@ +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlQueryable : QueryableProvider + { + public override ISugarQueryable With(string withString) + { + return this; + } + + public override ISugarQueryable PartitionBy(string groupFileds) + { + this.GroupBy(groupFileds); + return this; + } + } + public class MySqlQueryable : QueryableProvider + { + + } + public class MySqlQueryable : QueryableProvider + { + + } + public class MySqlQueryable : QueryableProvider + { + + } + public class MySqlQueryable : QueryableProvider + { + + } + public class MySqlQueryable : QueryableProvider + { + + } + public class MySqlQueryable : QueryableProvider + { + + } + public class MySqlQueryable : QueryableProvider + { + + } + public class MySqlQueryable : QueryableProvider + { + + } + public class MySqlQueryable : QueryableProvider + { + + } + public class MySqlQueryable : QueryableProvider + { + + } + public class MySqlQueryable : QueryableProvider + { + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlBlukCopy.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlBlukCopy.cs new file mode 100644 index 000000000..34ab90990 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlBlukCopy.cs @@ -0,0 +1,202 @@ +using MySqlConnector; +using System; +using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlBlukCopy + { + internal SqlSugarProvider Context { get; set; } + internal ISqlBuilder Builder { get; set; } + internal T[] Entitys { get; set; } + internal string Chara { get; set; } + private MySqlBlukCopy() + { + + } + public MySqlBlukCopy(SqlSugarProvider context, ISqlBuilder builder, T []entitys) + { + this.Context = context; + this.Builder = builder; + this.Entitys = entitys; + } + public bool ExecuteBulkCopy(string characterSet) + { + this.Chara = characterSet; + return ExecuteBulkCopy(); + } + + public bool ExecuteBulkCopy() + { + var IsBulkLoad = false; + if (Entitys == null || Entitys.Length <= 0) + return IsBulkLoad; + if (Entitys.First() == null && Entitys.Length ==1) + return IsBulkLoad; + DataTable dt = new DataTable(); + Type type = typeof(T); + var entity = this.Context.EntityMaintenance.GetEntityInfo(); + dt.TableName = this.Builder.GetTranslationColumnName(entity.DbTableName); + //if (this.Context.MappingTables != null && this.Context.MappingTables.Any(it => it.EntityName == it.EntityName)) + //{ + // dt.TableName = this.Builder.GetTranslationColumnName(this.Context.MappingTables.First(it => it.EntityName == it.EntityName).DbTableName); + //} + //创建属性的集合 + List pList = new List(); + //把所有的public属性加入到集合 并添加DataTable的列 + Array.ForEach(entity.Columns.ToArray(), p => { + if (!p.IsIgnore&& !p.IsOnlyIgnoreInsert) + { + pList.Add(p.PropertyInfo); dt.Columns.Add(p.DbColumnName); + } + }); + DataRow row = null; + foreach (T item in Entitys) + { + row = dt.NewRow(); + pList.ForEach(p => + { + var name = p.Name; + if (entity.Columns.Any(it => it.PropertyName == name)) + { + name = entity.Columns.First(it => it.PropertyName == name).DbColumnName; + } + row[name] = GetValue(p, item); + }); + dt.Rows.Add(row); + } + var dllPath =Path.Combine(AppDomain.CurrentDomain.BaseDirectory , "failFiles"); + DirectoryInfo dir = new DirectoryInfo(dllPath); + if (!dir.Exists) + { + dir.Create(); + } + var fileName =Path.Combine( dllPath , Guid.NewGuid().ToString() + ".csv"); + var dataTableToCsv = DataTableToCsvString(dt); + File.WriteAllText(fileName, dataTableToCsv, new UTF8Encoding(false)); + MySqlConnection conn = this.Context.Ado.Connection as MySqlConnection; + try + { + this.Context.Ado.Open(); + // IsolationLevel.Parse + MySqlBulkLoader bulk = new MySqlBulkLoader(conn) + { + CharacterSet = GetChara(), + FieldTerminator = ",", + FieldQuotationCharacter = '"', + EscapeCharacter = '"', + LineTerminator = Environment.NewLine, + FileName = fileName, + NumberOfLinesToSkip = 0, + TableName = dt.TableName, + Local = true, + }; + bulk.Columns.AddRange(dt.Columns.Cast().Select(colum => colum.ColumnName).Distinct().ToArray()); + IsBulkLoad = bulk.Load() > 0; + //执行成功才删除文件 + if (IsBulkLoad && File.Exists(fileName)) + { + File.Delete(fileName); + } + } + catch (MySqlException ex) + { + throw ex; + } + finally + { + CloseDb(); + } + return IsBulkLoad; ; + } + + public Task ExecuteBulkCopyAsync() + { + return Task.FromResult(ExecuteBulkCopy()); + } + + public Task ExecuteBulkCopyAsync(string characterSet) + { + this.Chara = characterSet; + return Task.FromResult(ExecuteBulkCopy()); + } + + #region Helper + private string GetChara() + { + if (this.Chara == null) + { + return "UTF8"; + } + else + { + return this.Chara; + } + } + + private void CloseDb() + { + if (this.Context.CurrentConnectionConfig.IsAutoCloseConnection && this.Context.Ado.Transaction == null) + { + this.Context.Ado.Connection.Close(); + } + } + + /// + ///DataTable to CSV + /// + /// datatable + /// CSV + public string DataTableToCsvString(DataTable table) + { + if (table.Rows.Count == 0) + return ""; + StringBuilder sb = new StringBuilder(); + DataColumn colum; + foreach (DataRow row in table.Rows) + { + for (int i = 0; i < table.Columns.Count; i++) + { + colum = table.Columns[i]; + if (i != 0) sb.Append(","); + if (colum.DataType == typeof(string) && (row[colum].ToString().Contains(",") || row[colum].ToString().Contains("\r") || row[colum].ToString().Contains("\""))) + { + sb.Append("\"" + row[colum].ToString().Replace("\"", "\"\"") + "\""); + } + else if (colum.DataType == typeof(bool)) + { + sb.Append(row[colum].ObjToBool() ? 1 : 0); + } + else if (colum.DataType == UtilConstants.DateType&& row[colum] != null && row[colum] != DBNull.Value) + { + sb.Append(row[colum].ObjToDate().ToString("yyyy-MM-dd HH:mm:ss.fff")); + } + else sb.Append(row[colum].ToString()); + } + sb.AppendLine(); + } + return sb.ToString(); + } + + + private static object GetValue(PropertyInfo p, T item) + { + var result= p.GetValue(item, null); + if (result != null && UtilMethods.GetUnderType(p.PropertyType) == UtilConstants.BoolType) + { + if (result.ObjToBool() == false) + { + result = null; + } + } + return result; + } + + #endregion + } +} \ No newline at end of file diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlBuilder.cs new file mode 100644 index 000000000..be8609927 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlBuilder.cs @@ -0,0 +1,26 @@ +using System; +using System.Linq; +using System.Text.RegularExpressions; + +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlBuilder : SqlBuilderProvider + { + public override string SqlTranslationLeft { get { return "`"; } } + public override string SqlTranslationRight { get { return "`"; } } + public override string SqlDateNow + { + get + { + return "sysdate()"; + } + } + public override string FullSqlDateNow + { + get + { + return "select sysdate()"; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlDeleteBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlDeleteBuilder.cs new file mode 100644 index 000000000..0002adc45 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlDeleteBuilder.cs @@ -0,0 +1,7 @@ +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlDeleteBuilder : DeleteBuilder + { + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlExpressionContext.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlExpressionContext.cs new file mode 100644 index 000000000..ff102ec34 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlExpressionContext.cs @@ -0,0 +1,154 @@ +using System; +using System.Linq; +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlExpressionContext : ExpressionContext, ILambdaExpressions + { + public SqlSugarProvider Context { get; set; } + public MySqlExpressionContext() + { + base.DbMehtods = new MySqlMethod(); + } + public override string SqlTranslationLeft { get { return "`"; } } + public override string SqlTranslationRight { get { return "`"; } } + } + public class MySqlMethod : DefaultDbMethod, IDbMethods + { + public override string DateValue(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + if (parameter.MemberName != null && parameter.MemberName is DateTime) + { + return string.Format(" {0}('{1}') ", parameter2.MemberValue, parameter.MemberName); + } + else + { + return string.Format(" {0}({1}) ", parameter2.MemberValue, 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(" (TIMESTAMPDIFF(day,date({0}),date({1}))=0) ", parameter.MemberName, parameter2.MemberName); ; + } + + public override string DateIsSameByType(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var parameter3 = model.Args[2]; + return string.Format(" (TIMESTAMPDIFF({2},{0},{1})=0) ", parameter.MemberName, parameter2.MemberName, parameter3.MemberValue); + } + + public override string DateAddByType(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var parameter3 = model.Args[2]; + return string.Format(" (DATE_ADD({1} , INTERVAL {2} {0})) ", 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(" (DATE_ADD({0}, INTERVAL {1} day)) ", parameter.MemberName, parameter2.MemberName); + } + + public override string ToInt32(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS SIGNED)", parameter.MemberName); + } + + public override string ToInt64(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS SIGNED)", parameter.MemberName); + } + + public override string ToString(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS CHAR)", parameter.MemberName); + } + + public override string ToGuid(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS CHAR)", 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 SIGNED)", 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) + ") "; + } + public override string IsNull(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter1 = model.Args[1]; + return string.Format("IFNULL({0},{1})", parameter.MemberName, parameter1.MemberName); + } + public override string GetDate() + { + return "NOW()"; + } + + public override string GetRandom() + { + return "rand()"; + } + + public override string CharIndex(MethodCallExpressionModel model) + { + return string.Format("instr ({0},{1})", model.Args[0].MemberName, model.Args[1].MemberName); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlFastBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlFastBuilder.cs new file mode 100644 index 000000000..bc788a94a --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlFastBuilder.cs @@ -0,0 +1,74 @@ +using MySqlConnector; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.MySqlConnectorCore +{ + + public class MySqlFastBuilder:FastBuilder,IFastBuilder + { + public override string UpdateSql { get; set; } = @"UPDATE {1} TM INNER JOIN {2} TE ON {3} SET {0} "; + public async Task ExecuteBulkCopyAsync(DataTable dt) + { + + var dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "failFiles"); + DirectoryInfo dir = new DirectoryInfo(dllPath); + if (!dir.Exists) + { + dir.Create(); + } + var fileName = Path.Combine(dllPath, Guid.NewGuid().ToString() + ".csv"); + var dataTableToCsv =new MySqlBlukCopy(this.Context.Context,null,null).DataTableToCsvString(dt); + File.WriteAllText(fileName, dataTableToCsv, new UTF8Encoding(false)); + MySqlConnection conn = this.Context.Ado.Connection as MySqlConnection; + int result = 0; + try + { + this.Context.Ado.Open(); + // IsolationLevel.Parse + MySqlBulkLoader bulk = new MySqlBulkLoader(conn) + { + CharacterSet = "UTF8", + FieldTerminator = ",", + FieldQuotationCharacter = '"', + EscapeCharacter = '"', + LineTerminator = Environment.NewLine, + FileName = fileName, + NumberOfLinesToSkip = 0, + TableName = dt.TableName, + Local = true, + }; + bulk.Columns.AddRange(dt.Columns.Cast().Select(colum =>new MySqlBuilder().GetTranslationColumnName(colum.ColumnName)).Distinct().ToArray()); + result= await bulk.LoadAsync(); + //执行成功才删除文件 + if (File.Exists(fileName)) + { + File.Delete(fileName); + } + } + catch (MySqlException ex) + { + throw ex; + } + finally + { + CloseDb(); + } + return result; + } + public override async Task CreateTempAsync(DataTable dt) + { + var queryable = this.Context.Queryable(); + var tableName = queryable.SqlBuilder.GetTranslationTableName(dt.TableName); + dt.TableName = "temp"+SnowFlakeSingle.instance.getID(); + var sql = queryable.AS(tableName).Where(it => false).ToSql().Key; + await this.Context.Ado.ExecuteCommandAsync($"Create TEMPORARY table {dt.TableName}({sql}) "); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlInsertBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlInsertBuilder.cs new file mode 100644 index 000000000..dcbd8b5f5 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlInsertBuilder.cs @@ -0,0 +1,136 @@ +using System; +using System.Linq; +using System.Text; + +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlInsertBuilder : InsertBuilder + { + public override string SqlTemplate + { + get + { + if (IsReturnIdentity) + { + return @"INSERT INTO {0} + ({1}) + VALUES + ({2}) ;SELECT LAST_INSERT_ID();"; + } + else + { + return @"INSERT INTO {0} + ({1}) + VALUES + ({2}) ;"; + + } + } + } + public override object FormatValue(object value) + { + var n = "N"; + if (this.Context.CurrentConnectionConfig.MoreSettings != null && this.Context.CurrentConnectionConfig.MoreSettings.DisableNvarchar) + { + n = ""; + } + if (value == null) + { + return "NULL"; + } + else + { + var type = UtilMethods.GetUnderType(value.GetType()); + if (type == UtilConstants.DateType) + { + var date = value.ObjToDate(); + if (date < Convert.ToDateTime("1900-1-1")) + { + date = Convert.ToDateTime("1900-1-1"); + } + return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'"; + } + else if (type == UtilConstants.ByteArrayType) + { + string bytesString = "0x" + BitConverter.ToString((byte[])value).Replace("-", ""); + 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 n+"'" + GetString(value).ToSqlFilter() + "'"; + } + else + { + return n+"'" + GetString(value) + "'"; + } + } + } + private string GetString(object value) + { + var result = value.ToString(); + if (result.HasValue() && result.Contains("\\")) + { + result = result.Replace("\\", "\\\\"); + } + return result; + } + + 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 => Builder.SqlParameterKeyWord + it.DbColumnName)); + return string.Format(SqlTemplate, GetTableNameString, columnsString, columnParametersString); + } + else + { + StringBuilder batchInsetrSql = new StringBuilder(); + batchInsetrSql.Append("INSERT INTO " + GetTableNameString + " "); + batchInsetrSql.Append("("); + batchInsetrSql.Append(columnsString); + batchInsetrSql.Append(") VALUES"); + string insertColumns = ""; + foreach (var item in groupList) + { + batchInsetrSql.Append("("); + insertColumns = string.Join(",", item.Select(it => FormatValue(it.Value))); + batchInsetrSql.Append(insertColumns); + if (groupList.Last() == item) + { + batchInsetrSql.Append(") "); + } + else + { + batchInsetrSql.Append("), "); + } + } + + batchInsetrSql.AppendLine(";select @@IDENTITY"); + var result = batchInsetrSql.ToString(); + return result; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlQueryBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlQueryBuilder.cs new file mode 100644 index 000000000..cad86a505 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlQueryBuilder.cs @@ -0,0 +1,138 @@ +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace SqlSugar.MySqlConnectorCore +{ + public partial class MySqlQueryBuilder : QueryBuilder + { + #region Sql Template + public override string PageTempalte + { + get + { + /* + SELECT * FROM TABLE WHERE CONDITION ORDER BY ID DESC LIMIT 0,10 + */ + var template = "SELECT {0} FROM {1} {2} {3} {4} LIMIT {5},{6}"; + return template; + } + } + public override string DefaultOrderByTemplate + { + get + { + return "ORDER BY NOW() "; + } + } + + #endregion + + #region Common Methods + 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); + return result; + } + private string ToCountSqlString() + { + //base.AppendFilter(); + string oldOrderValue = this.OrderByValue; + string result = null; + sql = new StringBuilder(); + sql.AppendFormat(SqlTemplate, "Count(*)", 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; + return result; + } + public override string ToCountSql(string sql) + { + if (this.GroupByValue.HasValue()) + { + return base.ToCountSql(sql); + } + else + { + return ToCountSqlString(); + } + } + #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; + } + return result; + } + } + + #endregion + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlUpdateBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlUpdateBuilder.cs new file mode 100644 index 000000000..590027702 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/MySql/SqlBuilder/MySqlUpdateBuilder.cs @@ -0,0 +1,155 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace SqlSugar.MySqlConnectorCore +{ + public class MySqlUpdateBuilder : UpdateBuilder + { + public override string SqlTemplateBatch + { + get + { + return @"UPDATE {1} S {2} INNER JOIN ${{0}} SET {0} "; + } + } + public override string SqlTemplateJoin + { + get + { + return @" ( + {0} + + ) T ON {1} + "; + } + } + 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("S.{0}=T.{0}", Builder.GetTranslationColumnName(it.DbColumnName)); + return result; + })); + batchUpdateSql.AppendFormat(SqlTemplateBatch.ToString(), setValues, GetTableNameStringNoWith, TableWithString); + int i = 0; + 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 SELECT " + string.Join(",", columns.Select(it => string.Format(SqlTemplateBatchSelect, FormatValue(it.Value),this.Builder.GetTranslationColumnName(it.DbColumnName))))); + ++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 += Regex.Replace(item, " \\" + this.Builder.SqlTranslationLeft, "S." + this.Builder.SqlTranslationLeft); + } + } + if (PrimaryKeys.HasValue()) + { + foreach (var item in PrimaryKeys) + { + var isFirst = whereString == null; + whereString += (isFirst ? null : " AND "); + whereString += string.Format("S.{0}=T.{0}", Builder.GetTranslationColumnName(item)); + } + } + var format= string.Format(SqlTemplateJoin, updateTable, whereString); + batchUpdateSql.Replace("${0}",format); + batchUpdateSql.Append(";"); + } + return batchUpdateSql.ToString(); + } + public override object FormatValue(object value) + { + var n = "N"; + if (this.Context.CurrentConnectionConfig.MoreSettings != null&&this.Context.CurrentConnectionConfig.MoreSettings.DisableNvarchar) + { + n = ""; + } + if (value == null) + { + return "NULL"; + } + else + { + var type = UtilMethods.GetUnderType(value.GetType()); + if (type == UtilConstants.DateType) + { + var date = value.ObjToDate(); + if (date < Convert.ToDateTime("1900-1-1")) + { + date = Convert.ToDateTime("1900-1-1"); + } + return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'"; + } + else if (type == UtilConstants.ByteArrayType) + { + string bytesString = "0x" + BitConverter.ToString((byte[])value).Replace("-", ""); + 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 n+"'" + GetString(value).ToSqlFilter() + "'"; + } + else + { + return n+"'" + GetString(value) + "'"; + } + } + } + private string GetString(object value) + { + var result = value.ToString(); + if (result.HasValue() && result.Contains("\\")) + { + result = result.Replace("\\", "\\\\"); + } + return result; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/SqlSugar.MySqlConnectorCore.csproj b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/SqlSugar.MySqlConnectorCore.csproj new file mode 100644 index 000000000..bfb51edda --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/SqlSugar.MySqlConnectorCore.csproj @@ -0,0 +1,15 @@ + + + + netstandard2.1 + + + + + + + + + + + diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/ErrorMessage.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/ErrorMessage.cs new file mode 100644 index 000000000..2f21ff2ed --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/ErrorMessage.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +namespace SqlSugar.MySqlConnectorCore +{ + 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/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/FileHelper.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/FileHelper.cs new file mode 100644 index 000000000..e2298d439 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/FileHelper.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace SqlSugar.MySqlConnectorCore +{ + 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/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilConstants.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilConstants.cs new file mode 100644 index 000000000..414bf0dc5 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilConstants.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Text; +namespace SqlSugar.MySqlConnectorCore +{ + 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/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilExtensions.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilExtensions.cs new file mode 100644 index 000000000..238dc5514 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilExtensions.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +namespace SqlSugar.MySqlConnectorCore +{ + /// + ///Common Extensions for external users + /// + public static class UtilExtensions + { + 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/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilMethods.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilMethods.cs new file mode 100644 index 000000000..d2043fd8f --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/UtilMethods.cs @@ -0,0 +1,493 @@ +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.MySqlConnectorCore +{ + public class UtilMethods + { + + 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/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/ValidateExtensions.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/ValidateExtensions.cs new file mode 100644 index 000000000..29149b17f --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.MySqlConnectorCore/Tools/ValidateExtensions.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +namespace SqlSugar.MySqlConnectorCore +{ + 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/SqlSeverTest/SqlSugar/Abstract/AdoProvider/AdoProvider.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/AdoProvider/AdoProvider.cs index 8cfcef645..b3397bb53 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/AdoProvider/AdoProvider.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/AdoProvider/AdoProvider.cs @@ -1253,7 +1253,7 @@ namespace SqlSugar { this.CancellationToken = null; } - private void Async() + protected void Async() { if (this.Context.Root != null && this.Context.Root.AsyncId == null) { @@ -1272,7 +1272,7 @@ namespace SqlSugar } } - private void ExecuteProcessingSQL(ref string sql, SugarParameter[] parameters) + protected void ExecuteProcessingSQL(ref string sql, SugarParameter[] parameters) { var result = this.ProcessingEventStartingSQL(sql, parameters); sql = result.Key; @@ -1361,18 +1361,18 @@ namespace SqlSugar if (parameters == null) return null; return base.GetParameters(parameters, propertyInfo, this.SqlParameterKeyWord); } - private bool IsAutoClose() + protected bool IsAutoClose() { return this.Context.CurrentConnectionConfig.IsAutoCloseConnection && this.Transaction == null; } - private bool IsMasterSlaveSeparation + protected bool IsMasterSlaveSeparation { get { return this.Context.CurrentConnectionConfig.SlaveConnectionConfigs.HasValue() && this.IsDisableMasterSlaveSeparation == false; } } - private void SetConnectionStart(string sql) + protected void SetConnectionStart(string sql) { if (this.Transaction == null && this.IsMasterSlaveSeparation && IsRead(sql)) { @@ -1408,7 +1408,7 @@ namespace SqlSugar return result.Count() == 0; } - private void SetConnectionEnd(string sql) + protected void SetConnectionEnd(string sql) { if (this.IsMasterSlaveSeparation && IsRead(sql) && this.Transaction == null) { @@ -1424,11 +1424,11 @@ namespace SqlSugar return result; } - private void ExecuteErrorEvent(string sql, SugarParameter[] parameters, Exception ex) + protected void ExecuteErrorEvent(string sql, SugarParameter[] parameters, Exception ex) { ErrorEvent(new SqlSugarException(this.Context, ex, sql, parameters)); } - private void InitParameters(ref string sql, SugarParameter[] parameters) + protected void InitParameters(ref string sql, SugarParameter[] parameters) { if (parameters.HasValue()) { diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/FastestProvider/Private.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/FastestProvider/Private.cs index 3e928bc8d..28d37d45f 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/FastestProvider/Private.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/FastestProvider/Private.cs @@ -23,6 +23,8 @@ namespace SqlSugar return new OracleFastBuilder(this.entityInfo); case DbType.PostgreSQL: return new PostgreSQLFastBuilder(this.entityInfo); + case DbType.MySqlConnector: + return InstanceFactory.CreateInstance("SqlSugar.MySqlConnector.MySqlFastBuilder"); case DbType.Dm: break; case DbType.Kdbndp: @@ -56,7 +58,7 @@ namespace SqlSugar } dt.TableName = GetTableName(); var columns = entityInfo.Columns; - var isMySql = this.context.CurrentConnectionConfig.DbType == DbType.MySql; + var isMySql = this.context.CurrentConnectionConfig.DbType.IsIn(DbType.MySql, DbType.MySqlConnector); foreach (var item in datas) { var dr = dt.NewRow(); diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs index 5e89ea92f..73466e287 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs @@ -381,6 +381,16 @@ namespace SqlSugar case DbType.Oscar: DependencyManagement.TryOscar(); break; + case DbType.MySqlConnector: + InstanceFactory.CustomTypeName = SugarCompatible.IsFramework?"SqlSugar.MySqlConnector": "SqlSugar.MySqlConnectorCore"; + break; + case DbType.Access: + InstanceFactory.CustomTypeName = SugarCompatible.IsFramework?"SqlSugar.Access": "SqlSugar.AccessCore"; + break; + case DbType.Custom: + Check.Exception(config?.MoreSettings?.CustomNugetDllName == null,ErrorMessage.GetThrowMessage("if DbType is Custmon , ConnectionConfig.MoreSettings.CustomNugetDbName is not null", "DbType是Custom ,而需要设置外部数据库支持dll名称。示例: ConnectionConfig.MoreSettings.CustomNugetDllName=\"SqlSugar.DB2\" , 设置完后我们需要引用SqlSugar.DB2.dll ")); + InstanceFactory.CustomTypeName = config.MoreSettings.CustomNugetDllName; + break; default: throw new Exception("ConnectionConfig.DbType is null"); } diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/UpdateProvider/UpdateableProvider.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/UpdateProvider/UpdateableProvider.cs index 5ca8ebe55..3eaec21ec 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/UpdateProvider/UpdateableProvider.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Abstract/UpdateProvider/UpdateableProvider.cs @@ -429,7 +429,9 @@ namespace SqlSugar private bool UpdateObjectNotWhere() { - return this.Context.CurrentConnectionConfig.DbType != DbType.MySql && this.Context.CurrentConnectionConfig.DbType != DbType.SqlServer; + return this.Context.CurrentConnectionConfig.DbType != DbType.MySql + && this.Context.CurrentConnectionConfig.DbType!=DbType.MySqlConnector + && this.Context.CurrentConnectionConfig.DbType != DbType.SqlServer; } private void AppendSets() diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Entities/ConnMoreSettings.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Entities/ConnMoreSettings.cs index 6a0b0d0e2..bdab95bf4 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Entities/ConnMoreSettings.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Entities/ConnMoreSettings.cs @@ -14,5 +14,6 @@ namespace SqlSugar public bool PgSqlIsAutoToLower = true; public int DefaultCacheDurationInSeconds { get; set; } public bool? TableEnumIsString { get; set; } + public string CustomNugetDllName { get; set; } } } diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Enum/DbType.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Enum/DbType.cs index bac17890e..b69d5140e 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Enum/DbType.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Enum/DbType.cs @@ -14,6 +14,9 @@ namespace SqlSugar PostgreSQL, Dm, Kdbndp, - Oscar + Oscar, + MySqlConnector, + Access, + Custom=900 } } diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve.cs index 9db19e4bc..641c4fc56 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve.cs @@ -635,6 +635,10 @@ namespace SqlSugar type = DbType.Oracle; else if (this.Context is PostgreSQLExpressionContext) type = DbType.PostgreSQL; + else if (this.Context.GetType().Name.StartsWith("MySql")) + { + type = DbType.MySql; + } return this.Context.SqlFuncServices.First(it => it.UniqueMethodName == name).MethodValue(model, type, this.Context); } else @@ -1092,7 +1096,9 @@ namespace SqlSugar } private bool IsMySql() { - return this.Context is MySqlExpressionContext; + var name = this.Context.GetType().Name; + var result= (name =="MySqlExpressionContext"); + return result; } private bool IsSqlite() { diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/InstanceFactory.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/InstanceFactory.cs index 049b07468..30974c68e 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/InstanceFactory.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/InstanceFactory.cs @@ -11,6 +11,7 @@ namespace SqlSugar { static Assembly assembly = Assembly.GetExecutingAssembly(); static Dictionary typeCache = new Dictionary(); + public static string CustomTypeName = ""; public static bool NoCache = false; public static void RemoveCache() @@ -25,14 +26,14 @@ namespace SqlSugar { return new SqlServerQueryable(); } - else if (currentConnectionConfig.DbType == DbType.MySql) + else if (currentConnectionConfig.DbType == DbType.MySql) { return new MySqlQueryable(); } else if (currentConnectionConfig.DbType == DbType.PostgreSQL) { return new PostgreSQLQueryable(); - } + } else { string className = "Queryable"; @@ -302,7 +303,26 @@ namespace SqlSugar private static string GetClassName(string type, string name) { - return UtilConstants.AssemblyName + "." + type + name; + if (type == "MySqlConnector") + { + return "SqlSugar.MySqlConnector.MySql" + name; + } + else if (type == "Access") + { + return "SqlSugar.MySqlConnector.Access" + name; + } + else if (type == "Custom") + { + return "SqlSugar.MySqlConnector.MySql" + name; + } + else + { + if (!string.IsNullOrEmpty(CustomTypeName)) + { + type = CustomTypeName; + } + return UtilConstants.AssemblyName + "." + type + name; + } } #region CreateInstance @@ -390,7 +410,14 @@ namespace SqlSugar { lock (typeCache) { - type = Type.GetType(className + "`" + types.Length, true).MakeGenericType(types); + if (string.IsNullOrEmpty(CustomTypeName)) + { + type = Type.GetType(className + "`" + types.Length, true).MakeGenericType(types); + } + else + { + type = GetCustomTypeByClass(className + "`" + types.Length).MakeGenericType(types); + } Check.ArgumentNullException(type, string.Format(ErrorMessage.ObjNotExist, className)); if (!typeCache.ContainsKey(cacheKey)) { @@ -403,8 +430,16 @@ namespace SqlSugar } private static Restult NoCacheGetCacheInstance(string className, Type[] types) { - - Type type = Type.GetType(className + "`" + types.Length, true).MakeGenericType(types); + + Type type = null; + if (string.IsNullOrEmpty(CustomTypeName)) + { + type = Type.GetType(className + "`" + types.Length, true).MakeGenericType(types); + } + else + { + type = GetCustomTypeByClass(className + "`" + types.Length).MakeGenericType(types); + } var result = (Restult)Activator.CreateInstance(type, true); return result; } @@ -452,10 +487,37 @@ namespace SqlSugar } private static T NoCacheGetCacheInstance(string className) { - Type type = assembly.GetType(className); + Type type = null; + if (string.IsNullOrEmpty(CustomTypeName)) + { + type=assembly.GetType(className); + } + else + { + type = GetCustomTypeByClass(className); + } var result = (T)Activator.CreateInstance(type, true); return result; } + + internal static Type GetCustomTypeByClass(string className) + { + var key = "Assembly_"+ CustomTypeName+assembly.GetHashCode(); + var newAssembly = new ReflectionInoCacheService().GetOrCreate(key, () => { + try + { + return Assembly.LoadFrom(CustomTypeName + ".dll"); + } + catch + { + var message = "Not Found " + CustomTypeName + ".dll"; + Check.Exception(true, message); + return null; + } + }); + Type type = newAssembly.GetType(className); + return type; + } #endregion } }