diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln b/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln index b30f03d14..e0ed0e34d 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln @@ -29,9 +29,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbFirstRazorTest", "DbFirst 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}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SqlSugar.MySqlConnectorCore", "SqlSugar.MySqlConnectorCore\SqlSugar.MySqlConnectorCore.csproj", "{D22873F3-80E1-4415-9CD6-21B1C7EEA4A0}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySqlConnectorTest", "MySqlConnectorTest\MySqlConnectorTest.csproj", "{1509863D-FEB5-4CC4-9C92-7EBE308B731E}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MySqlConnectorTest", "MySqlConnectorTest\MySqlConnectorTest.csproj", "{1509863D-FEB5-4CC4-9C92-7EBE308B731E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SqlSugar.AccessCore", "SqlSugar.AccessCore\SqlSugar.AccessCore.csproj", "{DD0C850D-86E5-4FFF-BFF3-8797EB448B47}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -95,12 +97,17 @@ Global {1509863D-FEB5-4CC4-9C92-7EBE308B731E}.Debug|Any CPU.Build.0 = Debug|Any CPU {1509863D-FEB5-4CC4-9C92-7EBE308B731E}.Release|Any CPU.ActiveCfg = Release|Any CPU {1509863D-FEB5-4CC4-9C92-7EBE308B731E}.Release|Any CPU.Build.0 = Release|Any CPU + {DD0C850D-86E5-4FFF-BFF3-8797EB448B47}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DD0C850D-86E5-4FFF-BFF3-8797EB448B47}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DD0C850D-86E5-4FFF-BFF3-8797EB448B47}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DD0C850D-86E5-4FFF-BFF3-8797EB448B47}.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} + {DD0C850D-86E5-4FFF-BFF3-8797EB448B47} = {88992AAF-146B-4253-9AD7-493E8F415B57} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {230A85B9-54F1-41B1-B1DA-80086581B2B4} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/AccessProvider.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/AccessProvider.cs new file mode 100644 index 000000000..59fef04e1 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/AccessProvider.cs @@ -0,0 +1,187 @@ +using SqlSugar.Access; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.Odbc; +using System.Data.OleDb; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +namespace SqlSugar.Access +{ + public class AccessProvider : AdoProvider + { + public AccessProvider() { } + public override IDbConnection Connection + { + get + { + if (base._DbConnection == null) + { + try + { + base._DbConnection = new OleDbConnection(base.Context.CurrentConnectionConfig.ConnectionString); + } + catch (Exception ex) + { + Check.Exception(true,ex.Message); + } + } + return base._DbConnection; + } + set + { + base._DbConnection = value; + } + } + /// + /// Only SqlServer + /// + /// + public override void BeginTran(string transactionName) + { + CheckConnection(); + base.Transaction = ((OleDbConnection)this.Connection).BeginTransaction(); + } + /// + /// Only SqlServer + /// + /// + /// + public override void BeginTran(IsolationLevel iso, string transactionName) + { + CheckConnection(); + base.Transaction = ((OleDbConnection)this.Connection).BeginTransaction(iso); + } + public override IDataAdapter GetAdapter() + { + return new OleDbDataAdapter(); + } + public override DbCommand GetCommand(string sql, SugarParameter[] parameters) + { + OleDbCommand sqlCommand = new OleDbCommand(sql, (OleDbConnection)this.Connection); + sqlCommand.CommandType = this.CommandType; + sqlCommand.CommandTimeout = this.CommandTimeOut; + if (this.Transaction != null) + { + sqlCommand.Transaction = (OleDbTransaction)this.Transaction; + } + if (parameters.HasValue()) + { + OleDbParameter[] ipars = GetSqlParameter(parameters); + sqlCommand.Parameters.AddRange(ipars); + } + CheckConnection(); + return sqlCommand; + } + public override void SetCommandToAdapter(IDataAdapter dataAdapter, DbCommand command) + { + ((OleDbDataAdapter)dataAdapter).SelectCommand = (OleDbCommand)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; + OleDbParameter[] result = new OleDbParameter[parameters.Length]; + int index = 0; + foreach (var parameter in parameters) + { + if (parameter.Value == null) parameter.Value = DBNull.Value; + var sqlParameter = new OleDbParameter(); + sqlParameter.ParameterName = parameter.ParameterName; + //sqlParameter.UdtTypeName = parameter.UdtTypeName; + sqlParameter.Size = parameter.Size; + sqlParameter.Value = parameter.Value; + sqlParameter.DbType = parameter.DbType; + sqlParameter.Direction = parameter.Direction; + 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); + } + ++index; + } + return result; + } + /// + /// if mysql return MySqlParameter[] pars + /// if sqlerver return SqlParameter[] pars ... + /// + /// + /// + public OleDbParameter[] GetSqlParameter(params SugarParameter[] parameters) + { + var isVarchar =IsVarchar(); + if (parameters == null || parameters.Length == 0) return null; + OleDbParameter[] result = new OleDbParameter[parameters.Length]; + int index = 0; + foreach (var parameter in parameters) + { + if (parameter.Value == null) parameter.Value = DBNull.Value; + var sqlParameter = new OleDbParameter(); + sqlParameter.ParameterName = parameter.ParameterName; + //sqlParameter.UdtTypeName = parameter.UdtTypeName; + sqlParameter.Size = parameter.Size; + sqlParameter.Value = parameter.Value; + sqlParameter.DbType = parameter.DbType; + var isTime = parameter.DbType == System.Data.DbType.DateTime; + if (isTime) + { + sqlParameter.DbType = System.Data.DbType.String; + sqlParameter.Value = sqlParameter.Value.ToString(); + } + if (sqlParameter.Value!=null&& sqlParameter.Value != DBNull.Value && sqlParameter.DbType == System.Data.DbType.DateTime) + { + var date = Convert.ToDateTime(sqlParameter.Value); + if (date==DateTime.MinValue) + { + sqlParameter.Value = Convert.ToDateTime("1753/01/01"); + } + } + if (parameter.Direction == 0) + { + parameter.Direction = ParameterDirection.Input; + } + sqlParameter.Direction = parameter.Direction; + result[index] = sqlParameter; + //if (parameter.TypeName.HasValue()) { + // sqlParameter.TypeName = parameter.TypeName; + // sqlParameter.SqlDbType = SqlDbType.Structured; + // sqlParameter.DbType = System.Data.DbType.Object; + //} + 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; + } + + ++index; + } + return result; + } + private bool IsVarchar() + { + if (this.Context.CurrentConnectionConfig.MoreSettings != null && this.Context.CurrentConnectionConfig.MoreSettings.DisableNvarchar) + { + return true; + } + return false; + } + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/CodeFirst/AccessCodeFirst.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/CodeFirst/AccessCodeFirst.cs new file mode 100644 index 000000000..e9bf91660 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/CodeFirst/AccessCodeFirst.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar.Access +{ + public class AccessCodeFirst : CodeFirstProvider + { + protected override string GetTableName(EntityInfo entityInfo) + { + var table= this.Context.EntityMaintenance.GetTableName(entityInfo.EntityName); + var tableArray = table.Split('.'); + var noFormat = table.Split(']').Length==1; + if (tableArray.Length > 1 && noFormat) + { + var dbMain = new SqlServerDbMaintenance() { Context = this.Context }; + var schmes = dbMain.GetSchemas(); + if (!schmes.Any(it => it.EqualCase(tableArray.First()))) + { + return tableArray.Last(); + } + else + { + return dbMain.SqlBuilder.GetTranslationTableName(table); + } + } + else + { + return table; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/DbBind/AccessDbBind.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/DbBind/AccessDbBind.cs new file mode 100644 index 000000000..099a5f67f --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/DbBind/AccessDbBind.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +namespace SqlSugar.Access +{ + public class AccessDbBind : DbBindProvider + { + 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("varchar",CSharpDataType.@string), + new KeyValuePair("nvarchar",CSharpDataType.@string), + new KeyValuePair("sql_variant",CSharpDataType.@string), + new KeyValuePair("text",CSharpDataType.@string), + new KeyValuePair("char",CSharpDataType.@string), + new KeyValuePair("ntext",CSharpDataType.@string), + new KeyValuePair("nchar",CSharpDataType.@string), + new KeyValuePair("hierarchyid",CSharpDataType.@string), + new KeyValuePair("bigint",CSharpDataType.@long), + new KeyValuePair("bit",CSharpDataType.@bool), + new KeyValuePair("datetime",CSharpDataType.DateTime), + new KeyValuePair("time",CSharpDataType.DateTime), + new KeyValuePair("smalldatetime",CSharpDataType.DateTime), + new KeyValuePair("timestamp",CSharpDataType.byteArray), + new KeyValuePair("datetime2",CSharpDataType.DateTime), + new KeyValuePair("date",CSharpDataType.DateTime), + new KeyValuePair("decimal",CSharpDataType.@decimal), + new KeyValuePair("single",CSharpDataType.@decimal), + new KeyValuePair("money",CSharpDataType.@decimal), + new KeyValuePair("numeric",CSharpDataType.@decimal), + new KeyValuePair("smallmoney",CSharpDataType.@decimal), + new KeyValuePair("float",CSharpDataType.@double), + new KeyValuePair("float",CSharpDataType.Single), + new KeyValuePair("real",CSharpDataType.@float), + new KeyValuePair("smallint",CSharpDataType.@short), + new KeyValuePair("tinyint",CSharpDataType.@byte), + new KeyValuePair("uniqueidentifier",CSharpDataType.Guid), + new KeyValuePair("binary",CSharpDataType.byteArray), + new KeyValuePair("image",CSharpDataType.byteArray), + new KeyValuePair("varbinary",CSharpDataType.byteArray), + new KeyValuePair("datetimeoffset", CSharpDataType.DateTimeOffset), + new KeyValuePair("datetimeoffset", CSharpDataType.DateTime)}; + }; + +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/DbFirst/AccessDbFirst.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/DbFirst/AccessDbFirst.cs new file mode 100644 index 000000000..b9a8c2bb7 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/DbFirst/AccessDbFirst.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar.Access +{ + public class AccessDbFirst : DbFirstProvider + { + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/DbMaintenance/AccessDbMaintenance.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/DbMaintenance/AccessDbMaintenance.cs new file mode 100644 index 000000000..db2dc5bfb --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/DbMaintenance/AccessDbMaintenance.cs @@ -0,0 +1,529 @@ +using SqlSugar.Access; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.OleDb; +using System.Linq; +using System.Text; + +namespace SqlSugar.Access +{ + public class AccessDbMaintenance : DbMaintenanceProvider + { + #region DML + protected override string GetDataBaseSql + { + get + { + return "SELECT NAME FROM MASTER.DBO.SYSDATABASES ORDER BY NAME"; + } + } + protected override string GetColumnInfosByTableNameSql + { + get + { + string sql = @"SELECT sysobjects.name AS TableName, + syscolumns.Id AS TableId, + syscolumns.name AS DbColumnName, + systypes.name AS DataType, + COLUMNPROPERTY(syscolumns.id,syscolumns.name,'PRECISION') as [length], + isnull(COLUMNPROPERTY(syscolumns.id,syscolumns.name,'Scale'),0) as Scale, + isnull(COLUMNPROPERTY(syscolumns.id,syscolumns.name,'Scale'),0) as DecimalDigits, + sys.extended_properties.[value] AS [ColumnDescription], + syscomments.text AS DefaultValue, + syscolumns.isnullable AS IsNullable, + columnproperty(syscolumns.id,syscolumns.name,'IsIdentity')as IsIdentity, + (CASE + WHEN EXISTS + ( + select 1 + from sysindexes i + join sysindexkeys k on i.id = k.id and i.indid = k.indid + join sysobjects o on i.id = o.id + join syscolumns c on i.id=c.id and k.colid = c.colid + where o.xtype = 'U' + and exists(select 1 from sysobjects where xtype = 'PK' and name = i.name) + and o.name=sysobjects.name and c.name=syscolumns.name + ) THEN 1 + ELSE 0 + END) AS IsPrimaryKey + FROM syscolumns + INNER JOIN systypes ON syscolumns.xtype = systypes.xtype + LEFT JOIN sysobjects ON syscolumns.id = sysobjects.id + LEFT OUTER JOIN sys.extended_properties ON (sys.extended_properties.minor_id = syscolumns.colid + AND sys.extended_properties.major_id = syscolumns.id) + LEFT OUTER JOIN syscomments ON syscolumns.cdefault = syscomments.id + WHERE syscolumns.id IN + (SELECT id + FROM sysobjects + WHERE upper(xtype) IN('U', + 'V') ) + AND (systypes.name <> 'sysname') + AND sysobjects.name='{0}' + AND systypes.name<>'geometry' + AND systypes.name<>'geography' + ORDER BY syscolumns.colid"; + return sql; + } + } + protected override string GetTableInfoListSql + { + get + { + return @"SELECT s.Name,Convert(varchar(max),tbp.value) as Description + FROM sysobjects s + LEFT JOIN sys.extended_properties as tbp ON s.id=tbp.major_id and tbp.minor_id=0 AND (tbp.Name='MS_Description' OR tbp.Name is null) WHERE s.xtype IN('U') "; + } + } + protected override string GetViewInfoListSql + { + get + { + return @"SELECT s.Name,Convert(varchar(max),tbp.value) as Description + FROM sysobjects s + LEFT JOIN sys.extended_properties as tbp ON s.id=tbp.major_id and tbp.minor_id=0 AND (tbp.Name='MS_Description' OR tbp.Name is null) WHERE s.xtype IN('V') "; + } + } + #endregion + + #region DDL + protected override string CreateDataBaseSql + { + get + { + return @"create database {0} "; + } + } + protected override string AddPrimaryKeySql + { + get + { + return "ALTER TABLE {0} ADD CONSTRAINT {1} PRIMARY KEY({2})"; + } + } + 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}"; + } + } + protected override string BackupDataBaseSql + { + get + { + return @"USE master;BACKUP DATABASE {0} TO disk = '{1}'"; + } + } + protected override string CreateTableSql + { + get + { + return "CREATE TABLE {0}(\r\n{1})"; + } + } + protected override string CreateTableColumn + { + get + { + return "{0} {1}{2} {3} {4} {5}"; + } + } + protected override string TruncateTableSql + { + get + { + return "TRUNCATE TABLE {0}"; + } + } + protected override string BackupTableSql + { + get + { + return "SELECT TOP {0} * INTO {1} FROM {2}"; + } + } + protected override string DropTableSql + { + get + { + return "DROP TABLE {0}"; + } + } + protected override string DropColumnToTableSql + { + get + { + return "ALTER TABLE {0} DROP COLUMN {1}"; + } + } + protected override string DropConstraintSql + { + get + { + return "ALTER TABLE {0} DROP CONSTRAINT {1}"; + } + } + protected override string RenameColumnSql + { + get + { + return "exec sp_rename '{0}.{1}','{2}','column';"; + } + } + protected override string AddColumnRemarkSql + { + get + { + return "EXECUTE sp_addextendedproperty N'MS_Description', '{2}', N'user', N'dbo', N'table', N'{1}', N'column', N'{0}'"; ; + } + } + + protected override string DeleteColumnRemarkSql + { + get + { + return "EXEC sp_dropextendedproperty 'MS_Description','user',dbo,'table','{1}','column','{0}'"; + } + + } + + protected override string IsAnyColumnRemarkSql + { + get + { + return @"SELECT" + + " A.name AS table_name," + + " B.name AS column_name," + + " C.value AS column_description" + + " FROM sys.tables A" + + " LEFT JOIN sys.extended_properties C ON C.major_id = A.object_id" + + " LEFT JOIN sys.columns B ON B.object_id = A.object_id AND C.minor_id = B.column_id" + + " INNER JOIN sys.schemas SC ON SC.schema_id = A.schema_id AND SC.name = 'dbo'" + + " WHERE A.name = '{1}' and b.name = '{0}'"; + + } + } + + protected override string AddTableRemarkSql + { + get + { + return "EXECUTE sp_addextendedproperty N'MS_Description', '{1}', N'user', N'dbo', N'table', N'{0}', NULL, NULL"; + } + } + + protected override string DeleteTableRemarkSql + { + get + { + return "EXEC sp_dropextendedproperty 'MS_Description','user',dbo,'table','{0}' "; + } + + } + + protected override string IsAnyTableRemarkSql + { + get + { + return @"SELECT 1 AS ID"; + } + + } + + protected override string RenameTableSql + { + get + { + return "EXEC sp_rename '{0}','{1}'"; + } + } + + protected override string CreateIndexSql + { + get + { + return "CREATE {3} NONCLUSTERED INDEX Index_{0}_{2} ON {0}({1})"; + } + } + protected override string AddDefaultValueSql + { + get + { + return "alter table {0} ADD DEFAULT '{2}' FOR {1}"; + } + } + protected override string IsAnyIndexSql + { + get + { + return "select count(*) from sys.indexes where name='{0}'"; + } + } + #endregion + + #region Check + protected override string CheckSystemTablePermissionsSql + { + get + { + return "select 1 AS ID "; + } + } + #endregion + + #region Scattered + protected override string CreateTableNull + { + get + { + return "NULL"; + } + } + protected override string CreateTableNotNull + { + get + { + return "NOT NULL"; + } + } + protected override string CreateTablePirmaryKey + { + get + { + return "PRIMARY KEY"; + } + } + protected override string CreateTableIdentity + { + get + { + return "IDENTITY(1,1)"; + } + } + + #endregion + + #region Methods + public override bool AddRemark(EntityInfo entity) + { + return true; + } + public override void AddDefaultValue(EntityInfo entityInfo) + { + //base.AddDefaultValue(entityInfo); + } + public override List GetViewInfoList(bool isCache = true) + { + return new List(); + } + public override List GetTableInfoList(bool isCache = true) + { + bool isOpen = Open(); + var table = (this.Context.Ado.Connection as OleDbConnection).GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "Table" }); + var result = table + .Rows.Cast().Select(it => new DbTableInfo + { + + Name = it["TABLE_NAME"] + "", + Description = it["DESCRIPTION"] + "" + }).ToList(); + Close(isOpen); + return result; + } + + private void Close(bool isOpen) + { + if (this.Context.CurrentConnectionConfig.IsAutoCloseConnection = true && isOpen) + { + this.Context.Ado.Connection.Close(); + } + } + + private bool Open() + { + var isOpen = false; + if (this.Context.CurrentConnectionConfig.IsAutoCloseConnection = true && this.Context.Ado.Connection.State == ConnectionState.Closed) + { + this.Context.Ado.Connection.Open(); + isOpen = true; + } + + return isOpen; + } + + public List GetSchemas() + { + return this.Context.Ado.SqlQuery("SELECT name FROM sys.schemas where name <> 'dbo'"); + } + public override bool DeleteTableRemark(string tableName) + { + string sql = string.Format(this.DeleteTableRemarkSql, tableName); + if (tableName.Contains(".")) + { + var schemas = GetSchemas(); + var tableSchemas = this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').First()); + if (schemas.Any(y => y.EqualCase(tableSchemas))) + { + sql = string.Format(this.DeleteTableRemarkSql, this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').Last())); + sql = sql.Replace(",dbo,", $",{tableSchemas},").Replace("'user'", "'SCHEMA'"); + } + } + this.Context.Ado.ExecuteCommand(sql); + return true; + } + public override bool IsAnyTableRemark(string tableName) + { + string sql = string.Format(this.IsAnyTableRemarkSql, tableName); + if (tableName.Contains(".")) + { + var schemas = GetSchemas(); + var tableSchemas = this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').First()); + if (schemas.Any(y => y.EqualCase(tableSchemas))) + { + sql = string.Format(this.IsAnyTableRemarkSql, this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').Last())); + sql = sql.Replace("'dbo'", $"'{tableSchemas}'"); + } + } + var dt = this.Context.Ado.GetDataTable(sql); + return dt.Rows != null && dt.Rows.Count > 0; + } + public override bool AddTableRemark(string tableName, string description) + { + string sql = string.Format(this.AddTableRemarkSql, tableName, description); + if (tableName.Contains(".")) + { + var schemas = GetSchemas(); + var tableSchemas =this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').First()); + if (schemas.Any(y => y.EqualCase(tableSchemas))) + { + sql = string.Format(this.AddTableRemarkSql, this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').Last()), description); + sql = sql.Replace("N'dbo'", $"N'{tableSchemas}'").Replace("N'user'", "N'SCHEMA'"); + } + } + this.Context.Ado.ExecuteCommand(sql); + return true; + } + public override bool AddDefaultValue(string tableName, string columnName, string defaultValue) + { + if (defaultValue == "''") + { + defaultValue = ""; + } + var template = AddDefaultValueSql; + if (defaultValue != null && defaultValue.ToLower() == "getdate()") + { + template = template.Replace("'{2}'", "{2}"); + } + string sql = string.Format(template, tableName, columnName, defaultValue); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + + /// + ///by current connection string + /// + /// + /// + public override bool CreateDatabase(string databaseName, string databaseDirectory = null) + { + throw new Exception("Access no support CreateDatabase"); + } + public override bool CreateTable(string tableName, List columns, bool isCreatePrimaryKey = true) + { + tableName = this.SqlBuilder.GetTranslationTableName(tableName); + foreach (var item in columns) + { + if (item.DataType == "decimal" && item.DecimalDigits == 0 && item.Length == 0) + { + item.DecimalDigits = 4; + item.Length = 18; + } + } + string sql = GetCreateTableSql(tableName, columns); + this.Context.Ado.ExecuteCommand(sql); + if (isCreatePrimaryKey) + { + var pkColumns = columns.Where(it => it.IsPrimarykey).ToList(); + if (pkColumns.Count > 1) + { + this.Context.DbMaintenance.AddPrimaryKeys(tableName, pkColumns.Select(it => it.DbColumnName).ToArray()); + } + else + { + foreach (var item in pkColumns) + { + this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName); + } + } + } + return true; + } + public override List GetColumnInfosByTableName(string tableName, bool isCache = true) + { + + List columns = new List(); + var dt = this.Context.Ado.GetDataTable("select top 8 * from " +this.SqlBuilder.GetTranslationTableName(tableName)); + var oleDb = (this.Context.Ado.Connection as OleDbConnection); + bool isOpen = Open(); + DataTable columnTable = oleDb.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null,tableName, null }); + DataTable Pk = oleDb.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, new string[] { null, null, tableName }); + foreach (DataRow dr in columnTable.Rows) + { + DbColumnInfo info = new DbColumnInfo(); + info.TableName = tableName; + info.DbColumnName = dr["COLUMN_NAME"] + ""; + info.IsNullable = Convert.ToBoolean(dr["IS_NULLABLE"]); + info.DataType = dt.Columns[info.DbColumnName].DataType.Name; + if (info.DataType.EqualCase( "int32")) + { + info.DataType = "int"; + } + else if (info.DataType.EqualCase("int64")) + { + info.DataType = "long"; + } + if (info.DataType.EqualCase("string") ) + { + info.Length = dr["CHARACTER_MAXIMUM_LENGTH"].ObjToInt(); + } + if (info.DataType.EqualCase("Decimal")) + { + info.Length = dr["numeric_precision"].ObjToInt(); + info.Scale=info.DecimalDigits = dr["numeric_scale"].ObjToInt(); + } + foreach (DataRow pkRow in Pk.Rows) + { + if (pkRow["COLUMN_NAME"].ObjToString() == dr["COLUMN_NAME"].ObjToString()) + { + info.IsPrimarykey = true; + if (info.DataType == "int") + { + info.IsIdentity = true; + } + } + } + columns.Add(info); + } + Close(isOpen); + return columns; + } + public override bool RenameColumn(string tableName, string oldColumnName, string newColumnName) + { + tableName = this.SqlBuilder.GetTranslationTableName(tableName); + oldColumnName = this.SqlBuilder.GetTranslationColumnName(oldColumnName); + newColumnName = this.SqlBuilder.GetNoTranslationColumnName(newColumnName); + string sql = string.Format(this.RenameColumnSql, tableName, oldColumnName, newColumnName); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + #endregion + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/Queryable/AccessQueryable.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/Queryable/AccessQueryable.cs new file mode 100644 index 000000000..7ee438dea --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/Queryable/AccessQueryable.cs @@ -0,0 +1,58 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Text; + +namespace SqlSugar.Access +{ + public class AccessQueryable:QueryableProvider + { + + } + public class AccessQueryable : QueryableProvider + { + + } + public class AccessQueryable : QueryableProvider + { + + } + public class AccessQueryable : QueryableProvider + { + + } + public class AccessQueryable : QueryableProvider + { + + } + public class AccessQueryable : QueryableProvider + { + + } + public class AccessQueryable : QueryableProvider + { + + } + public class AccessQueryable : QueryableProvider + { + + } + public class AccessQueryable : QueryableProvider + { + + } + public class AccessQueryable : QueryableProvider + { + + } + public class AccessQueryable : QueryableProvider + { + + } + public class AccessQueryable : QueryableProvider + { + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessBlukCopy.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessBlukCopy.cs new file mode 100644 index 000000000..e49c41e93 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessBlukCopy.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.Access +{ + public class AccessBlukCopy + { + internal List> DbColumnInfoList { get; set; } + internal SqlSugarProvider Context { get; set; } + internal ISqlBuilder Builder { get; set; } + internal InsertBuilder InsertBuilder { get; set; } + internal object[] Inserts { get; set; } + + public int ExecuteBulkCopy() + { + throw new NotSupportedException(); + } + + public async Task ExecuteBulkCopyAsync() + { + throw new NotSupportedException(); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessBuilder.cs new file mode 100644 index 000000000..1e268e2e7 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessBuilder.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace SqlSugar.Access +{ + public class AccessBuilder : SqlBuilderProvider + { + public override string SqlTranslationLeft { get { return "["; } } + public override string SqlTranslationRight { get { return "]"; } } + public override string SqlDateNow { get { return " NOW()"; } } + public override string FullSqlDateNow { get { return "SELECT NOW()"; } } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessDeleteBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessDeleteBuilder.cs new file mode 100644 index 000000000..40a5d9c5c --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessDeleteBuilder.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.Access +{ + public class AccessDeleteBuilder : DeleteBuilder + { + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessExpressionContext.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessExpressionContext.cs new file mode 100644 index 000000000..f30ecb5ec --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessExpressionContext.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.Access +{ + public partial class AccessExpressionContext : ExpressionContext, ILambdaExpressions + { + public SqlSugarProvider Context { get; set; } + public AccessExpressionContext() + { + base.DbMehtods = new AccessMethod(); + } + + } + public partial class AccessMethod : DefaultDbMethod, IDbMethods + { + public override string ToDate(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CDate({0}) ", parameter.MemberName); + } + public override string ToBool(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CDate({0}) ", parameter.MemberName); + } + public override string ToInt32(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CInt({0}) ", parameter.MemberName); + } + public override string ToString(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CVar({0}) ", parameter.MemberName); + } + public override string ToDateShort(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" Format$({0},\"Long Date\") ", parameter.MemberName); + } + public override string DateValue(MethodCallExpressionModel model) + { + var type = ""; + if (model.Args[1].MemberValue.ObjToString() == "Day") + { + type = "d"; + } + if (model.Args[1].MemberValue.ObjToString() == "Month") + { + type = "m"; + } + if (model.Args[1].MemberValue.ObjToString() == "Year") + { + type = "yyyy"; + } + if (model.Args[1].MemberValue.ObjToString() == DateType.Minute.ToString()) + { + type = "M"; + } + if (model.Args[1].MemberValue.ObjToString() == DateType.Second.ToString()) + { + type = "s"; + } + return "DATEPART(\""+ type + "\", date())"; + } + public override string GetRandom() + { + return " rnd() "; + } + public override string GetDate() + { + return " NOW()"; + } + public override string HasValue(MethodCallExpressionModel model) + { + if (model.Args[0].Type == UtilConstants.GuidType) + { + var parameter = model.Args[0]; + return string.Format("( {0} IS NOT NULL )", parameter.MemberName); + } + else + { + var parameter = model.Args[0]; + return string.Format("( {0}<>'' AND {0} IS NOT NULL )", parameter.MemberName); + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessFastBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessFastBuilder.cs new file mode 100644 index 000000000..9966c401a --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessFastBuilder.cs @@ -0,0 +1,26 @@ +using Microsoft.Data.SqlClient; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.Access +{ + + public class AccessFastBuilder : FastBuilder,IFastBuilder + { + public async Task ExecuteBulkCopyAsync(DataTable dt) + { + + throw new NotSupportedException(); + } + public SqlBulkCopy GetBulkCopyInstance() + { + throw new NotSupportedException(); + } + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessInsertBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessInsertBuilder.cs new file mode 100644 index 000000000..d8d132a1a --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessInsertBuilder.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.Access +{ + public class AccessInsertBuilder : InsertBuilder + { + public override string SqlTemplate + { + get + { + if (IsReturnIdentity) + { + return @"INSERT INTO {0} + ({1}) + VALUES + ({2}) ;"; + } + else + { + return @"INSERT INTO {0} + ({1}) + VALUES + ({2}) ;"; + + } + } + } + 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(); + int pageSize = 200; + if (this.EntityInfo.Columns.Count > 30) + { + pageSize = 50; + } + else if (this.EntityInfo.Columns.Count > 20) + { + pageSize = 100; + } + int pageIndex = 1; + int totalRecord = groupList.Count; + int pageCount = (totalRecord + pageSize - 1) / pageSize; + while (pageCount >= pageIndex) + { + batchInsetrSql.AppendFormat(SqlTemplateBatch, GetTableNameString, columnsString); + int i = 0; + foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList()) + { + var isFirst = i == 0; + if (!isFirst) + { + batchInsetrSql.Append(SqlTemplateBatchUnion); + } + batchInsetrSql.Append("\r\n SELECT " + string.Join(",", columns.Select(it => string.Format(SqlTemplateBatchSelect, FormatValue(it.Value), Builder.GetTranslationColumnName(it.DbColumnName))))); + ++i; + } + pageIndex++; + batchInsetrSql.Append("\r\n;\r\n"); + } + var result = batchInsetrSql.ToString(); + if (this.Context.CurrentConnectionConfig.DbType == DbType.SqlServer) + { + result += "select SCOPE_IDENTITY();"; + } + return result; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessQueryBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessQueryBuilder.cs new file mode 100644 index 000000000..9e9ef4210 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessQueryBuilder.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.Access +{ + public class AccessQueryBuilder : QueryBuilder + { + public override string SqlTemplate + { + get + { + return "SELECT {0}{"+UtilConstants.ReplaceKey+"} FROM {1}{2}{3}{4}"; + } + } + + public override string ToSqlString() + { + string oldOrderBy = this.OrderByValue; + string externalOrderBy = oldOrderBy; + var isIgnoreOrderBy = this.IsCount && this.PartitionByValue.IsNullOrEmpty(); + AppendFilter(); + sql = new StringBuilder(); + if (this.OrderByValue == null && (Skip != null || Take != null)) this.OrderByValue = " ORDER BY now() "; + if (this.PartitionByValue.HasValue()) + { + throw new Exception("sqlite no support partition by"); + } + var isFirst = (Skip == 0 || Skip == null) && Take == 1 && DisableTop == false; + var isRowNumber = (Skip != null || Take != null) && !isFirst; + var isPage = isRowNumber; + isRowNumber = false; + var oldSkip = Skip; + var oldTake = Take; + Skip = null; + Take = null; + var rowNumberString = string.Format(",ROW_NUMBER() OVER({0}) AS RowIndex ", GetOrderByString); + string groupByValue = GetGroupByString + HavingInfos; + string orderByValue = (!isRowNumber && this.OrderByValue.HasValue()) ? GetOrderByString : null; + if (isIgnoreOrderBy) { orderByValue = null; } + sql.AppendFormat(SqlTemplate, isFirst ? (" TOP 1 " + GetSelectValue) : GetSelectValue, GetTableNameString, GetWhereValueString, groupByValue, orderByValue); + sql.Replace(UtilConstants.ReplaceKey, isRowNumber ? (isIgnoreOrderBy ? null : rowNumberString) : null); + if (isIgnoreOrderBy) { this.OrderByValue = oldOrderBy; return sql.ToString(); } + var result = isFirst ? sql.ToString() : ToPageSql(sql.ToString(), this.Take, this.Skip); + if (ExternalPageIndex > 0) + { + throw new Exception("sqlite no support partition by"); + } + this.OrderByValue = oldOrderBy; + if (!string.IsNullOrEmpty(this.Offset)) + { + if (this.OrderByValue.IsNullOrEmpty()) + { + result += " ORDER BY now() "; + this.OrderByValue = " ORDER BY now() "; + } + result += this.Offset; + } + result = GetSqlQuerySql(result); + if (isPage) + { + var colums=this.Context.EntityMaintenance.GetEntityInfo(this.EntityType).Columns; + if (!colums.Any(x => x.IsPrimarykey)) + { + throw new Exception("sqlite page need primary key , entity name: "+ this.EntityName); + } + var pkName =this.Builder.GetTranslationColumnName(colums.Where(x => x.IsPrimarykey).First().DbColumnName); + var takeSql = $@" SELECT { (oldTake == null ? "" : ("Top " + oldTake)) } + *FROM({ result}) ACCTABLE1"; + var skipSql = $@" + WHERE {pkName} NOT IN + (SELECT { (oldSkip == null ? "" : ("Top " + oldSkip))} {pkName} FROM ({result}) ACCTABLE2 { this.OrderByValue })"; + if (oldSkip == 0) + { + result = takeSql; + } + else + { + result = takeSql+skipSql; + } + + } + return result; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessUpdateBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessUpdateBuilder.cs new file mode 100644 index 000000000..e5e58357c --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Access/SqlBuilder/AccessUpdateBuilder.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.Access +{ + public class AccessUpdateBuilder : UpdateBuilder + { + protected override string TomultipleSqlString(List> groupList) + { + throw new Exception("access no support batch update"); + } + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/SqlSugar.AccessCore.csproj b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/SqlSugar.AccessCore.csproj new file mode 100644 index 000000000..6f3d76dbb --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/SqlSugar.AccessCore.csproj @@ -0,0 +1,15 @@ + + + + netstandard2.1 + + + + + + + + + + + diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Tools/ErrorMessage.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Tools/ErrorMessage.cs new file mode 100644 index 000000000..4cd9041da --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Tools/ErrorMessage.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +namespace SqlSugar.Access +{ + 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.AccessCore/Tools/FileHelper.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Tools/FileHelper.cs new file mode 100644 index 000000000..65cc4b2b5 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Tools/FileHelper.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace SqlSugar.Access +{ + 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.AccessCore/Tools/UtilConstants.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Tools/UtilConstants.cs new file mode 100644 index 000000000..deef8b25f --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Tools/UtilConstants.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Text; +namespace SqlSugar.Access +{ + 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.AccessCore/Tools/UtilExtensions.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Tools/UtilExtensions.cs new file mode 100644 index 000000000..193788a9a --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Tools/UtilExtensions.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +namespace SqlSugar.Access +{ + /// + ///Common Extensions for external users + /// + public static class UtilExtensions + { + + public static bool EqualCase(this string thisValue, string equalValue) + { + if (thisValue != null && equalValue != null) + { + return thisValue.ToLower() == equalValue.ToLower(); + } + else + { + return thisValue == equalValue; + } + } + 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.AccessCore/Tools/UtilMethods.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Tools/UtilMethods.cs new file mode 100644 index 000000000..5186a788b --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/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.Access +{ + 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.AccessCore/Tools/ValidateExtensions.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/Tools/ValidateExtensions.cs new file mode 100644 index 000000000..a1d61cf2f --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar.AccessCore/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.Access +{ + 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/OnlyCore/DataExtensions.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/OnlyCore/DataExtensions.cs index c7938b1ea..6460f2601 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/OnlyCore/DataExtensions.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/OnlyCore/DataExtensions.cs @@ -1111,4 +1111,143 @@ namespace SqlSugar } } } + + + + /// + /// 数据填充器 + /// + public class OleDbDataAdapter : IDataAdapter + { + private SqlCommand command; + private string sql; + private SqlConnection _sqlConnection; + + /// + /// SqlDataAdapter + /// + /// + public OleDbDataAdapter(SqlCommand command) + { + this.command = command; + } + + public OleDbDataAdapter() + { + + } + + /// + /// SqlDataAdapter + /// + /// + /// + public OleDbDataAdapter(string sql, SqlConnection _sqlConnection) + { + this.sql = sql; + this._sqlConnection = _sqlConnection; + } + + /// + /// SelectCommand + /// + public SqlCommand SelectCommand + { + get + { + if (this.command == null) + { + this.command = new SqlCommand(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 (SqlDataReader 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 (SqlDataReader dr = command.ExecuteReader()) + { + do + { + var dt = new DataTable(); + var columns = dt.Columns; + var rows = dt.Rows; + for (int i = 0; i < dr.FieldCount; i++) + { + string name = dr.GetName(i).Trim(); + if (!columns.Contains(name)) + columns.Add(new DataColumn(name, dr.GetFieldType(i))); + else + { + columns.Add(new DataColumn(name + i, dr.GetFieldType(i))); + } + + } + + while (dr.Read()) + { + DataRow daRow = dt.NewRow(); + for (int i = 0; i < columns.Count; i++) + { + daRow[columns[i].ColumnName] = dr.GetValue(i); + } + dt.Rows.Add(daRow); + } + dt.AcceptChanges(); + ds.Tables.Add(dt); + } while (dr.NextResult()); + } + } + } } \ No newline at end of file