diff --git a/Src/Asp.Net/DmTest/App.config b/Src/Asp.Net/DmTest/App.config new file mode 100644 index 000000000..8e1564635 --- /dev/null +++ b/Src/Asp.Net/DmTest/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Src/Asp.Net/DmTest/Config.cs b/Src/Asp.Net/DmTest/Config.cs new file mode 100644 index 000000000..ea24f40bd --- /dev/null +++ b/Src/Asp.Net/DmTest/Config.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + /// + /// Setting up the database name does not require you to create the database + /// 设置好数据库名不需要你去手动建库 + /// + public class Config + { + /// + /// Account have permission to create database + /// 用有建库权限的数据库账号 + /// + public static string ConnectionString = "PORT=5236;DATABASE=DAMENG;HOST=localhost;PASSWORD=SYSDBA;USER ID=SYSDBA"; + /// + /// Account have permission to create database + /// 用有建库权限的数据库账号 + /// + public static string ConnectionString2 = "PORT=5236;DATABASE=DAMENG;HOST=localhost;PASSWORD=SYSDBA;USER ID=SYSDBA"; + /// + /// Account have permission to create database + /// 用有建库权限的数据库账号 + /// + public static string ConnectionString3 = "PORT=5236;DATABASE=DAMENG;HOST=localhost;PASSWORD=SYSDBA;USER ID=SYSDBA"; + } +} diff --git a/Src/Asp.Net/DmTest/Demo/Demo0_SqlSugarClient.cs b/Src/Asp.Net/DmTest/Demo/Demo0_SqlSugarClient.cs new file mode 100644 index 000000000..8ed1c8415 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/Demo0_SqlSugarClient.cs @@ -0,0 +1,416 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SqlSugar; +namespace OrmTest +{ + public class Demo0_SqlSugarClient + { + + public static void Init() + { + SqlSugarClient();//Create db + DbContext();//Optimizing SqlSugarClient usage + SingletonPattern();//Singleten Pattern + //DistributedTransactionExample(); + MasterSlave();//Read-write separation + CustomAttribute(); + } + + private static void MasterSlave() + { + Console.WriteLine(""); + Console.WriteLine("#### MasterSlave Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString,//Master Connection + DbType = DbType.Dm, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + SlaveConnectionConfigs = new List() { + new SlaveConnectionConfig() { HitRate=10, ConnectionString=Config.ConnectionString2 } , + new SlaveConnectionConfig() { HitRate=10, ConnectionString=Config.ConnectionString2 } + } + }); + db.Aop.OnLogExecuted = (s, p) => + { + Console.WriteLine(db.Ado.Connection.ConnectionString); + }; + Console.WriteLine("Master:"); + db.Insertable(new Order() { Name = "abc", CustomId = 1, CreateTime = DateTime.Now }).ExecuteCommand(); + Console.WriteLine("Slave:"); + db.Queryable().First(); + Console.WriteLine("#### MasterSlave End ####"); + } + + private static void SqlSugarClient() + { + //Create db + Console.WriteLine("#### SqlSugarClient Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + //If no exist create datebase + //db.DbMaintenance.CreateDatabase(); + + //Use db query + var dt = db.Ado.GetDataTable("select 1"); + + //Create tables + db.CodeFirst.InitTables(typeof(OrderItem),typeof(Order)); + var id = db.Insertable(new Order() { Name = "order1", CustomId = 1, Price = 0, CreateTime = DateTime.Now }).ExecuteReturnIdentity(); + + //Insert data + db.Insertable(new OrderItem() { OrderId = id, Price = 0, CreateTime=DateTime.Now }).ExecuteCommand(); + Console.WriteLine("#### SqlSugarClient End ####"); + + } + + private static void DbContext() + { + Console.WriteLine(""); + Console.WriteLine("#### DbContext Start ####"); + var insertObj = new Order { Name = "jack", CreateTime = DateTime.Now }; + var InsertObjs = new Order[] { insertObj }; + + DbContext context = new DbContext(); + + context.Db.CodeFirst.InitTables();//Create Tables + ; + var orderDb = context.OrderDb; + + //Select + var data1 = orderDb.GetById(1); + var data2 = orderDb.GetList(); + var data3 = orderDb.GetList(it => it.Id == 1); + var data4 = orderDb.GetSingle(it => it.Id == 1); + var p = new PageModel() { PageIndex = 1, PageSize = 2 }; + var data5 = orderDb.GetPageList(it => it.Name == "xx", p); + Console.Write(p.PageCount); + var data6 = orderDb.GetPageList(it => it.Name == "xx", p, it => it.Name, OrderByType.Asc); + Console.Write(p.PageCount); + List conModels = new List(); + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1", FieldValueConvertFunc=it=>Convert.ToInt32(it) });//id=1 + var data7 = orderDb.GetPageList(conModels, p, it => it.Name, OrderByType.Asc); + orderDb.AsQueryable().Where(x => x.Id == 1).ToList(); + + //Insert + orderDb.Insert(insertObj); + orderDb.InsertRange(InsertObjs); + var id = orderDb.InsertReturnIdentity(insertObj); + orderDb.AsInsertable(insertObj).ExecuteCommand(); + + + //Delete + orderDb.Delete(insertObj); + orderDb.DeleteById(11111); + orderDb.DeleteById(new int[] { 1111, 2222 }); + orderDb.Delete(it => it.Id == 1111); + orderDb.AsDeleteable().Where(it => it.Id == 1111).ExecuteCommand(); + + //Update + orderDb.Update(insertObj); + orderDb.UpdateRange(InsertObjs); + orderDb.Update(it => new Order() { Name = "a", }, it => it.Id == 1); + orderDb.AsUpdateable(insertObj).UpdateColumns(it => new { it.Name }).ExecuteCommand(); + + //Use Inherit DbContext + OrderDal dal = new OrderDal(); + var data = dal.GetById(1); + var list = dal.GetList(); + + Console.WriteLine("#### DbContext End ####"); + } + + private static void CustomAttribute() + { + Console.WriteLine(""); + Console.WriteLine("#### Custom Attribute Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.Dm, + IsAutoCloseConnection = true, + InitKeyType = InitKeyType.Attribute, + ConfigureExternalServices = new ConfigureExternalServices() + { + EntityService = (property, column) => + { + + var attributes = property.GetCustomAttributes(true);//get all attributes + + if (attributes.Any(it => it is KeyAttribute))// by attribute set primarykey + { + column.IsPrimarykey = true; + } + }, + EntityNameService = (type, entity) => + { + var attributes = type.GetCustomAttributes(true); + if (attributes.Any(it => it is TableAttribute)) + { + entity.DbTableName = (attributes.First(it => it is TableAttribute) as TableAttribute).Name; + } + } + } + }); + db.CodeFirst.InitTables();//Create Table + + db.Insertable(new AttributeTable() { Id = Guid.NewGuid().ToString(), Name = "Name" }).ExecuteCommand(); + var list = db.Queryable().ToList(); + + Console.WriteLine("#### Custom Attribute End ####"); + } + + + private static void SingletonPattern() + { + Console.WriteLine(""); + Console.WriteLine("#### Singleton Pattern Start ####"); + Console.WriteLine("Db_Id:" + singleDb.ContextID); + Console.WriteLine("Db_Id:" + singleDb.ContextID); + var task = new Task(() => + { + Console.WriteLine("Task DbId:" + singleDb.ContextID); + new Task(() => + { + Console.WriteLine("_Task_Task DbId:" + singleDb.ContextID); + Console.WriteLine("_Task_Task DbId:" + singleDb.ContextID); + + }).Start(); + Console.WriteLine("Task DbId:" + singleDb.ContextID); + }); + task.Start(); + task.Wait(); + System.Threading.Thread.Sleep(500); + Console.WriteLine(string.Join(",", singleDb.TempItems.Keys)); + + Console.WriteLine("#### Singleton Pattern end ####"); + } + + static SqlSugarClient singleDb = new SqlSugarClient( + new ConnectionConfig() + { + ConfigId = 1, + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents() + { + OnLogExecuting = (sql, p) => { Console.WriteLine(sql); } + } + }); + + + private static void DistributedTransactionExample() + { + Console.WriteLine(""); + Console.WriteLine("#### Distributed TransactionExample Start ####"); + SqlSugarClient db = new SqlSugarClient(new List() + { + new ConnectionConfig(){ ConfigId="1", DbType=DbType.Dm, ConnectionString=Config.ConnectionString,InitKeyType=InitKeyType.Attribute,IsAutoCloseConnection=true }, + new ConnectionConfig(){ ConfigId="2", DbType=DbType.Dm, ConnectionString=Config.ConnectionString2 ,InitKeyType=InitKeyType.Attribute ,IsAutoCloseConnection=true} + }); + + //use db1 + db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(Order), typeof(OrderItem));// + db.Insertable(new Order() { Name = "order1", CreateTime = DateTime.Now }).ExecuteCommand(); + Console.WriteLine(db.CurrentConnectionConfig.DbType + ":" + db.Queryable().Count()); + + //use db2 + db.ChangeDatabase("2"); + //db.DbMaintenance.CreateDatabase();//Create Database2 + db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(Order), typeof(OrderItem)); + db.Insertable(new Order() { Name = "order1", CreateTime = DateTime.Now }).ExecuteCommand(); + Console.WriteLine(db.CurrentConnectionConfig.DbType + ":" + db.Queryable().Count()); + + // Example 1 + Console.WriteLine("Example 1"); + try + { + db.BeginTran(); + + db.ChangeDatabase("1");//use db1 + db.Deleteable().ExecuteCommand(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use db2 + db.Deleteable().ExecuteCommand(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + throw new Exception(); + db.CommitTran(); + } + catch + { + db.RollbackTran(); + Console.WriteLine("---Roll back"); + db.ChangeDatabase("1");//use db1 + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use db2 + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + } + + + + // Example 2 + Console.WriteLine("Example 2"); + + var result=db.UseTran(() => + { + + db.ChangeDatabase("1");//use db1 + db.Deleteable().ExecuteCommand(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use db2 + db.Deleteable().ExecuteCommand(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + throw new Exception(""); + + }); + if (result.IsSuccess == false) { + Console.WriteLine("---Roll back"); + db.ChangeDatabase("1");//use db1 + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use db2 + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + } + + // Example 3 + Console.WriteLine("Example 3"); + + var result2 = db.UseTranAsync(() => + { + + db.ChangeDatabase("1");//use db1 + db.Deleteable().ExecuteCommand(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use db2 + db.Deleteable().ExecuteCommand(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + throw new Exception(""); + + }); + result2.Wait(); + if (result.IsSuccess == false) + { + Console.WriteLine("---Roll back"); + db.ChangeDatabase("1");//use sqlserver + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use mysql + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + } + + Console.WriteLine("#### Distributed TransactionExample End ####"); + } + } + + /// + /// DbContext Example 1 + /// + public class DbContext + { + + public SqlSugarClient Db; + public DbContext() + { + Db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.Dm, + IsAutoCloseConnection = true, + InitKeyType = InitKeyType.Attribute, + AopEvents = new AopEvents() + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + } + } + }); + } + public SimpleClient OrderDb => new SimpleClient(Db); + public SimpleClient OrderItemDb => new SimpleClient(Db); + } + + + public class OrderDal : DbContext + { + + } + /// + /// DbContext Example 2 + /// + /// + public class DbContext where T : class, new() + { + + public SqlSugarClient Db; + public DbContext() + { + Db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.Dm, + IsAutoCloseConnection = true, + InitKeyType = InitKeyType.Attribute, + AopEvents = new AopEvents() + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + } + } + }); + } + public SimpleClient CurrentDb => new SimpleClient(Db); + public virtual T GetById(int id) + { + return CurrentDb.GetById(id); + } + public virtual List GetList() + { + return CurrentDb.GetList(); + } + public virtual bool Delete(int id) + { + return CurrentDb.DeleteById(id); + } + } + +} diff --git a/Src/Asp.Net/DmTest/Demo/Demo1_Queryable.cs b/Src/Asp.Net/DmTest/Demo/Demo1_Queryable.cs new file mode 100644 index 000000000..d14fa8bf7 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/Demo1_Queryable.cs @@ -0,0 +1,341 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Data; +using System.Dynamic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + public class Demo1_Queryable + { + + public static void Init() + { + EasyExamples(); + QueryConditions(); + JoinTable(); + Async(); + NoEntity(); + Mapper(); + SqlFuncTest(); + Subquery(); + ReturnType(); + } + + private static void EasyExamples() + { + Console.WriteLine(""); + Console.WriteLine("#### Examples Start ####"); + var db = GetInstance(); + var dbTime = db.GetDate(); + var getAll = db.Queryable().ToList(); + var getOrderBy = db.Queryable().OrderBy(it => it.Name,OrderByType.Desc).ToList(); + var getOrderBy2 = db.Queryable().OrderBy(it => it.Id).OrderBy(it => it.Name, OrderByType.Desc).ToList(); + var getOrderBy3 = db.Queryable().OrderBy(it =>new { it.Name,it.Id}).ToList(); + var getRandom = db.Queryable().OrderBy(it => SqlFunc.GetRandom()).First(); + var getByPrimaryKey = db.Queryable().InSingle(2); + var getSingleOrDefault = db.Queryable().Where(it => it.Id == 1).Single(); + var getFirstOrDefault = db.Queryable().First(); + var getByWhere = db.Queryable().Where(it => it.Id == 1 || it.Name == "a").ToList(); + var getByWhere2 = db.Queryable().Where(it => it.Id == DateTime.Now.Year).ToList(); + var getByFuns = db.Queryable().Where(it => SqlFunc.IsNullOrEmpty(it.Name)).ToList(); + var getByFuns2 = db.Queryable().GroupBy(it => it.Name).Select(it => SqlFunc.AggregateDistinctCount(it.Price)).ToList(); + Console.WriteLine("#### Examples End ####"); + } + + private static void ReturnType() + { + Console.WriteLine(""); + Console.WriteLine("#### ReturnType Start ####"); + var db = GetInstance(); + List list = db.Queryable().ToList(); + + Order item = db.Queryable().First(it => it.Id == 1); + + DataTable dataTable = db.Queryable().Select(it => it.Id).ToDataTable(); + + var json = db.Queryable().ToJson(); + + List listInt = db.Queryable().Select(it => it.Id).ToList(); + + var dynamic = db.Queryable().Select().ToList(); + + var viewModel = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId , + JoinType.Left, o.CustomId == c.Id + )) + .Select().ToList(); + + var newDynamic = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, o.CustomId == c.Id + )) + .Select((o, i, c) => new { orderName = o.Name, cusName=c.Name }).ToList(); + + var newClass = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, o.CustomId == c.Id + )) + .Select((o, i, c) => new ViewOrder { Name=o.Name, CustomName=c.Name }).ToList(); + + + var oneClass = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, o.CustomId == c.Id + )) + .Select((o, i, c) => c).ToList(); + + var twoClass = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, o.CustomId == c.Id + )) + .Select((o, i, c) => new { o,i}).ToList(); + + List> ListDic = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, o.CustomId == c.Id + )) + .Select().ToList().Select(it => it.ToDictionary(x => x.Key, x => x.Value)).ToList(); + Console.WriteLine("#### ReturnType End ####"); + } + + private static void Subquery() + { + Console.WriteLine(""); + Console.WriteLine("#### Subquery Start ####"); + var db = GetInstance(); + + var list = db.Queryable().Take(10).Select(it => new + { + customName=SqlFunc.Subqueryable().Where("it.CustomId=id").Select(s=>s.Name), + customName2 = SqlFunc.Subqueryable().Where("it.CustomId = id").Where(s => true).Select(s => s.Name) + }).ToList(); + + var list2 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(i => i.OrderId == it.Id).Any()).ToList(); + + Console.WriteLine("#### Subquery End ####"); + } + + private static void SqlFuncTest() + { + Console.WriteLine(""); + Console.WriteLine("#### SqlFunc Start ####"); + var db = GetInstance(); + var index= db.Queryable().Select(it => SqlFunc.CharIndex("a", "cccacc")).First(); + + Console.WriteLine("#### SqlFunc End ####"); + } + + private static void Mapper() + { + Console.WriteLine(""); + Console.WriteLine("#### Mapper Start ####"); + var db = GetInstance(); + //Creater Table + db.CodeFirst.InitTables(typeof(Tree)); + db.DbMaintenance.TruncateTable("tree"); + db.Insertable(new Tree() { Id = 1, Name = "root" }).ExecuteCommand(); + db.Insertable(new Tree() { Id = 11, Name = "child1",ParentId=1 }).ExecuteCommand(); + db.Insertable(new Tree() { Id = 12, Name = "child2",ParentId=1 }).ExecuteCommand(); + db.Insertable(new Tree() { Id = 2, Name = "root" }).ExecuteCommand(); + db.Insertable(new Tree() { Id = 22, Name = "child3", ParentId = 2 }).ExecuteCommand(); + + // Same property name mapping,Both entities have parentId + var list = db.Queryable().Mapper(it => it.Parent, it => it.ParentId).ToList(); + + + //If both entities have parentId, I don't want to associate with parentId. + var list1 =db.Queryable() + //parent=(select * from parent where id=it.parentid) + .Mapper(it=>it.Parent,it=>it.ParentId, it=>it.Parent.Id) + //Child=(select * from parent where ParentId=it.id) + .Mapper(it => it.Child, it => it.Id, it => it.Parent.ParentId) + .ToList(); + //one to one + var list2 = db.Queryable().Mapper(it => it.Order, it => it.OrderId).ToList(); + + //one to many + var list3 = db.Queryable().Mapper(it => it.Items, it => it.Items.First().OrderId).ToList(); + + //many to many + db.CodeFirst.InitTables(); + + db.Insertable(new A() { Name = "A" }).ExecuteCommand(); + db.Insertable(new B() { Name = "B" }).ExecuteCommand(); + db.Insertable(new ABMapping() { AId = 1, BId = 1 }).ExecuteCommand(); + + var list4 = db.Queryable() + .Mapper(it => it.A, it => it.AId) + .Mapper(it => it.B, it => it.BId).ToList(); + + //Manual mode + var result = db.Queryable().Take(10).Select().Mapper((itemModel, cache) => + { + var allItems = cache.Get(orderList => { + var allIds = orderList.Select(it => it.Id).ToList(); + return db.Queryable().Where(it => allIds.Contains(it.OrderId)).ToList();//Execute only once + }); + itemModel.Items = allItems.Where(it => it.OrderId==itemModel.Id).ToList();//Every time it's executed + }).ToList(); + + Console.WriteLine("#### End Start ####"); + } + + private static void NoEntity() + { + Console.WriteLine(""); + Console.WriteLine("#### No Entity Start ####"); + var db = GetInstance(); + + var list = db.Queryable().AS("order").Where("id=id", new { id = 1 }).ToList(); + + var list2 = db.Queryable("o").AS("order").AddJoinInfo("OrderDetail", "i", "o.id=i.OrderId").Where("id=id", new { id = 1 }).Select("o.*").ToList(); + Console.WriteLine("#### No Entity End ####"); + } + + private static void JoinTable() + { + Console.WriteLine(""); + Console.WriteLine("#### Join Table Start ####"); + var db = GetInstance(); + + //Simple join + var list = db.Queryable((o, i, c) => o.Id == i.OrderId&&c.Id == o.CustomId) + .Select() + .ToList(); + + //Join table + var list2 = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, c.Id == o.CustomId + )) + .Select().ToList(); + + //Join queryable + var query1 = db.Queryable((o, i) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId + )) + .Where(o => o.Name == "jack"); + + var query2 = db.Queryable(); + var list3=db.Queryable(query1, query2,JoinType.Left, (p1, p2) => p1.CustomId == p2.Id).Select().ToList(); + + Console.WriteLine("#### Join Table End ####"); + } + + private static void QueryConditions() + { + Console.WriteLine(""); + Console.WriteLine("#### Query Conditions Start ####"); + + SqlSugarClient db = GetInstance(); + + /*** By expression***/ + + //id=@id + var list = db.Queryable().Where(it => it.Id == 1).ToList(); + //id=@id or name like '%'+@name+'%' + var list2 = db.Queryable().Where(it => it.Id == 1 || it.Name.Contains("jack")).ToList(); + + + //Create expression + var exp = Expressionable.Create() + .And(it => it.Id == 1) + .Or(it => it.Name.Contains("jack")).ToExpression(); + var list3 = db.Queryable().Where(exp).ToList(); + + + /*** By sql***/ + + //id=@id + var list4 = db.Queryable().Where("id=@id", new { id = 1 }).ToList(); + //id=@id or name like '%'+@name+'%' + var list5 = db.Queryable().Where("id=@id or name like @name ", new { id = 1, name = "%jack%" }).ToList(); + + + + /*** By dynamic***/ + + //id=1 + var conModels = new List(); + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" , FieldValueConvertFunc=it=>Convert.ToInt32(it) });//id=1 + var student = db.Queryable().Where(conModels).ToList(); + + //Complex use case + List Order = new List(); + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1", FieldValueConvertFunc = it => Convert.ToInt32(it) });//id=1 + //conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Like, FieldValue = "1", FieldValueConvertFunc = it => Convert.ToInt32(it) });// id like '%1%' + //conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.IsNullOrEmpty }); + //conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.In, FieldValue = "1,2,3" }); + //conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.NotIn, FieldValue = "1,2,3" }); + //conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.NoEqual, FieldValue = "1,2,3" }); + //conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.IsNot, FieldValue = null });// id is not null + + conModels.Add(new ConditionalCollections() + { + ConditionalList = new List>()// (id=1 or id=2 and id=1) + { + //new KeyValuePair( WhereType.And ,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" }), + new KeyValuePair (WhereType.Or,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" , FieldValueConvertFunc = it => Convert.ToInt32(it) }), + new KeyValuePair ( WhereType.And,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" ,FieldValueConvertFunc = it => Convert.ToInt32(it)}) + } + }); + var list6 = db.Queryable().Where(conModels).ToList(); + + /*** Conditional builder ***/ + + // use whereif + string name = ""; + int id = 1; + var query = db.Queryable() + .WhereIF(!string.IsNullOrEmpty(name), it => it.Name.Contains(name)) + .WhereIF(id > 0, it => it.Id == id).ToList(); + //clone new Queryable + var query2 = db.Queryable().Where(it => it.Id == 1); + var list7 = query2.Clone().Where(it => it.Name == "jack").ToList();//id=1 and name = jack + var list8 = query2.Clone().Where(it => it.Name == "tom").ToList();//id=1 and name = tom + + Console.WriteLine("#### Condition Screening End ####"); + + + + } + + private static void Async() + { + Console.WriteLine(""); + Console.WriteLine("#### Async Start ####"); + + SqlSugarClient db = GetInstance(); + var task1 = db.Queryable().FirstAsync(); + task1.Wait(); + var task2 = db.Queryable().Where(it => it.Id == 1).ToListAsync(); + + + task2.Wait(); + + Console.WriteLine("#### Async End ####"); + } + + private static SqlSugarClient GetInstance() + { + return new SqlSugarClient(new ConnectionConfig() + { + DbType = SqlSugar.DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/Demo2_Updateable.cs b/Src/Asp.Net/DmTest/Demo/Demo2_Updateable.cs new file mode 100644 index 000000000..b213283d8 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/Demo2_Updateable.cs @@ -0,0 +1,107 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo2_Updateable + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Updateable Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + + + /*** 1.entity or List ***/ + + var updateObj = new Order() { Id = 1, Name = "order1" }; + var updateObjs = new List { + new Order() { Id = 11, Name = "order11" }, + new Order() { Id = 12, Name = "order12" } + }; + + //update all columns by primary key + var result = db.Updateable(updateObj).ExecuteCommand();//update single + var result2 = db.Updateable(updateObjs).ExecuteCommand();//update List + + //Ignore Name and Price + var result3 = db.Updateable(updateObj).IgnoreColumns(it => new { it.CreateTime, it.Price }).ExecuteCommand(); + + //only update Name and CreateTime + var result4 = db.Updateable(updateObj).UpdateColumns(it => new { it.Name, it.CreateTime }).ExecuteCommand(); + + //If there is no primary key + var result5 = db.Updateable(updateObj).WhereColumns(it => new { it.Id }).ExecuteCommand();//update single by id + var result6 = db.Updateable(updateObjs).WhereColumns(it => new { it.Id }).ExecuteCommand();//update List by id + + + + + /*** 2.by expression ***/ + + //update name,createtime + var result7 = db.Updateable(it => new Order() { Name = "a", CreateTime = DateTime.Now }).Where(it => it.Id == 11).ExecuteCommand(); + var result71 = db.Updateable().SetColumns(it => new Order() { Name = "a", CreateTime = DateTime.Now }).Where(it => it.Id == 11).ExecuteCommand(); + //only update name + var result8 = db.Updateable(it => it.Name == "Name").Where(it => it.Id == 1).ExecuteCommand(); + var result81 = db.Updateable().SetColumns(it => it.Name == "Name" ).Where(it => it.Id == 1).ExecuteCommand(); + // + + + + + /*** 3.by Dictionary ***/ + var dt = new Dictionary(); + dt.Add("id", 1); + dt.Add("name", "abc"); + dt.Add("createTime", DateTime.Now); + var dtList = new List>(); + dtList.Add(dt); + + var t66 = db.Updateable(dt).AS("order").WhereColumns("id").ExecuteCommand(); + var t666 = db.Updateable(dtList).AS("order").WhereColumns("id").ExecuteCommand(); + + + + /*** 4.Other instructions ***/ + + var caseValue = "1"; + //Do not update NULL columns + db.Updateable(updateObj).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand(); + + //if 1 update name else if 2 update name,createtime + db.Updateable(updateObj) + .UpdateColumnsIF(caseValue == "1", it => new { it.Name }) + .UpdateColumnsIF(caseValue == "2", it => new { it.Name, it.CreateTime }) + .ExecuteCommand(); + //Use Lock + db.Updateable(updateObj).With(SqlWith.UpdLock).ExecuteCommand(); + + //Where Sql + db.Updateable(updateObj).Where("id=@x", new { x = 1 }).ExecuteCommand(); + + Console.WriteLine("#### Updateable End ####"); + } + + } +} \ No newline at end of file diff --git a/Src/Asp.Net/DmTest/Demo/Demo3_Insertable.cs b/Src/Asp.Net/DmTest/Demo/Demo3_Insertable.cs new file mode 100644 index 000000000..715dc433b --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/Demo3_Insertable.cs @@ -0,0 +1,56 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo3_Insertable + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Insertable Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + var insertObj = new Order() { Id = 1, Name = "order1",Price=0 }; + var updateObjs = new List { + new Order() { Id = 11, Name = "order11", Price=0 }, + new Order() { Id = 12, Name = "order12" , Price=0} + }; + + //Ignore CreateTime + db.Insertable(insertObj).IgnoreColumns(it => new { it.CreateTime }).ExecuteReturnIdentity();//get identity + db.Insertable(insertObj).IgnoreColumns("CreateTime").ExecuteReturnIdentity(); + + //Only insert Name and Price + db.Insertable(insertObj).InsertColumns(it => new { it.Name, it.Price }).ExecuteReturnIdentity(); + db.Insertable(insertObj).InsertColumns("Name", "Price").ExecuteReturnIdentity(); + + //ignore null columns + db.Insertable(updateObjs).ExecuteCommand();//get change row count + + //Use Lock + db.Insertable(insertObj).With(SqlWith.UpdLock).ExecuteCommand(); + + Console.WriteLine("#### Insertable End ####"); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/Demo4_Deleteable.cs b/Src/Asp.Net/DmTest/Demo/Demo4_Deleteable.cs new file mode 100644 index 000000000..1a380b214 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/Demo4_Deleteable.cs @@ -0,0 +1,48 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo4_Deleteable + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Deleteable Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + //by entity + db.Deleteable().Where(new Order() { Id = 1111 }).ExecuteCommand(); + + //by primary key + db.Deleteable().In(1111).ExecuteCommand(); + + //by primary key array + db.Deleteable().In(new int[] { 1111, 2222 }).ExecuteCommand(); + + //by expression + db.Deleteable().Where(it => it.Id == 11111).ExecuteCommand(); + + Console.WriteLine("#### Deleteable End ####"); + + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/Demo5_SqlQueryable.cs b/Src/Asp.Net/DmTest/Demo/Demo5_SqlQueryable.cs new file mode 100644 index 000000000..82a6c0394 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/Demo5_SqlQueryable.cs @@ -0,0 +1,36 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo5_SqlQueryable + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### SqlQueryable Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true + }); + + int total = 0; + var list = db.SqlQueryable("select * from \"ORDER\"").ToPageList(1, 2, ref total); + + + //by expression + var list2 = db.SqlQueryable("select * from \"ORDER\"").Where(it => it.Id == 1).ToPageList(1, 2); + //by sql + var list3 = db.SqlQueryable("select * from \"ORDER\"").Where("id=@id", new { id = 1 }).ToPageList(1, 2); + + Console.WriteLine("#### SqlQueryable End ####"); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/Demo6_Queue.cs b/Src/Asp.Net/DmTest/Demo/Demo6_Queue.cs new file mode 100644 index 000000000..3f54ff514 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/Demo6_Queue.cs @@ -0,0 +1,52 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo6_Queue + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Queue Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + db.Insertable(new Order() { Name = "a" }).AddQueue(); + db.Insertable(new Order() { Name = "b" }).AddQueue(); + db.SaveQueues(); + + + db.Insertable(new Order() { Name = "a" }).AddQueue(); + db.Insertable(new Order() { Name = "b" }).AddQueue(); + db.Insertable(new Order() { Name = "c" }).AddQueue(); + db.Insertable(new Order() { Name = "d" }).AddQueue(); + var ar = db.SaveQueuesAsync(); + ar.Wait(); + + db.Queryable().AddQueue(); + db.Queryable().AddQueue(); + db.AddQueue("select * from \"ORDER\" where id=@id", new { id = 10000 }); + var result2 = db.SaveQueues(); + + Console.WriteLine("#### Queue End ####"); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/Demo7_Ado.cs b/Src/Asp.Net/DmTest/Demo/Demo7_Ado.cs new file mode 100644 index 000000000..84278dd58 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/Demo7_Ado.cs @@ -0,0 +1,57 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo7_Ado + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Ado Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + //sql + var dt = db.Ado.GetDataTable("select * from \"ORDER\" where @id>0 or name=@name", new List(){ + new SugarParameter("@id",1), + new SugarParameter("@name","2") + }); + + //sql + var dt2 = db.Ado.GetDataTable("select * from \"ORDER\" where @id>0 or name=@name", new { id = 1, name = "2" }); + + //Stored Procedure + //var dt3 = db.Ado.UseStoredProcedure().GetDataTable("sp_school", new { name = "张三", age = 0 }); + //var nameP = new SugarParameter("@name", "张三"); + //var ageP = new SugarParameter("@age", null, true);//isOutput=true + //var dt4 = db.Ado.UseStoredProcedure().GetDataTable("sp_school", nameP, ageP); + + + + //There are many methods to under db.ado + var list= db.Ado.SqlQuery("select * from \"ORDER\" "); + var intValue=db.Ado.SqlQuerySingle("select 1"); + db.Ado.ExecuteCommand("delete from \"ORDER\" where id>1000"); + //db.Ado.xxx + Console.WriteLine("#### Ado End ####"); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/Demo8_Saveable.cs b/Src/Asp.Net/DmTest/Demo/Demo8_Saveable.cs new file mode 100644 index 000000000..256348255 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/Demo8_Saveable.cs @@ -0,0 +1,48 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo8_Saveable + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Saveable Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + + //insert or update + db.Saveable(new Order() { Id=1, Name="jack" }).ExecuteReturnEntity(); + + + //insert or update + db.Saveable(new Order() { Id = 1000, Name = "jack", CreateTime=DateTime.Now }) + .InsertColumns(it => new { it.Name,it.CreateTime, it.Price})//if insert into name,CreateTime,Price + .UpdateColumns(it => new { it.Name, it.CreateTime })//if update set name CreateTime + .ExecuteReturnEntity(); + + Console.WriteLine(""); + Console.WriteLine("#### Saveable End ####"); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/Demo9_EntityMain.cs b/Src/Asp.Net/DmTest/Demo/Demo9_EntityMain.cs new file mode 100644 index 000000000..91008aab0 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/Demo9_EntityMain.cs @@ -0,0 +1,46 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo9_EntityMain + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### EntityMain Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + var entityInfo = db.EntityMaintenance.GetEntityInfo(); + foreach (var column in entityInfo.Columns) + { + Console.WriteLine(column.DbColumnName); + } + + var dbColumnsName = db.EntityMaintenance.GetDbColumnName("Name"); + + var dbTableName = db.EntityMaintenance.GetTableName(); + + //more https://github.com/sunkaixuan/SqlSugar/wiki/9.EntityMain + Console.WriteLine("#### EntityMain End ####"); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/DemoA_DbMain.cs b/Src/Asp.Net/DmTest/Demo/DemoA_DbMain.cs new file mode 100644 index 000000000..539c6a6ea --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/DemoA_DbMain.cs @@ -0,0 +1,42 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoA_DbMain + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### DbMain Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + var tables = db.DbMaintenance.GetTableInfoList(); + foreach (var table in tables) + { + Console.WriteLine(table.Description); + } + //more https://github.com/sunkaixuan/SqlSugar/wiki/a.DbMain + Console.WriteLine("#### DbMain End ####"); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/DemoB_Aop.cs b/Src/Asp.Net/DmTest/Demo/DemoB_Aop.cs new file mode 100644 index 000000000..07b37808c --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/DemoB_Aop.cs @@ -0,0 +1,68 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoB_Aop + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Aop Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true + }); + db.Aop.OnLogExecuted = (sql, pars) => //SQL executed event + { + Console.WriteLine("OnLogExecuted"+sql); + }; + db.Aop.OnLogExecuting = (sql, pars) => //SQL executing event (pre-execution) + { + Console.WriteLine("OnLogExecuting" + sql); + }; + db.Aop.OnError = (exp) =>//SQL execution error event + { + //exp.sql + }; + db.Aop.OnExecutingChangeSql = (sql, pars) => //SQL executing event (pre-execution,SQL script can be modified) + { + return new KeyValuePair(sql, pars); + }; + db.Aop.OnDiffLogEvent = it =>//Get data changes + { + var editBeforeData = it.BeforeData; + var editAfterData = it.AfterData; + var sql = it.Sql; + var parameter = it.Parameters; + var businessData = it.BusinessData; + var time = it.Time; + var diffType = it.DiffType;//enum insert 、update and delete + Console.WriteLine(businessData); + Console.WriteLine(editBeforeData[0].Columns[1].Value); + Console.WriteLine("to"); + Console.WriteLine(editAfterData[0].Columns[1].Value); + //Write logic + }; + + + db.Queryable().ToList(); + db.Queryable().ToList(); + + //OnDiffLogEvent + var data = db.Queryable().First(); + data.Name = "changeName"; + db.Updateable(data).EnableDiffLogEvent("--update Order--").ExecuteCommand(); + + Console.WriteLine("#### Aop End ####"); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/DemoD_DbFirst.cs b/Src/Asp.Net/DmTest/Demo/DemoD_DbFirst.cs new file mode 100644 index 000000000..c7a987341 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/DemoD_DbFirst.cs @@ -0,0 +1,78 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + public class DemoD_DbFirst + { + public static void Init() + { + Console.WriteLine(); + Console.WriteLine("#### DbFirst Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + MoreSettings=new ConnMoreSettings() { + PgSqlIsAutoToLower=false + } + }); + + db.DbFirst.CreateClassFile("c:\\Demo\\1", "Models"); + + + db.DbFirst.Where("Student").CreateClassFile("c:\\Demo\\2", "Models"); + + + db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\3", "Models"); + + + db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\4", "Models"); + + + db.DbFirst.IsCreateAttribute().CreateClassFile("c:\\Demo\\5", "Models"); + + + db.DbFirst.IsCreateDefaultValue().CreateClassFile("c:\\Demo\\6", "Demo.Models"); + + + db.DbFirst. SettingClassTemplate(old => { return old;}) + .SettingNamespaceTemplate(old =>{ return old;}) + .SettingPropertyDescriptionTemplate(old => + { + return @" /// + /// Desc_New:{PropertyDescription} + /// Default_New:{DefaultValue} + /// Nullable_New:{IsNullable} + /// "; + }) + .SettingPropertyTemplate(old =>{return old;}) + .SettingConstructorTemplate(old =>{return old; }) + .CreateClassFile("c:\\Demo\\7"); + + + + foreach (var item in db.DbMaintenance.GetTableInfoList()) + { + string entityName = item.Name.ToUpper();/*Format class name*/ + db.MappingTables.Add(entityName , item.Name); + foreach (var col in db.DbMaintenance.GetColumnInfosByTableName(item.Name)) + { + db.MappingColumns.Add(col.DbColumnName.ToUpper() /*Format class property name*/, col.DbColumnName, entityName); + } + } + db.DbFirst.IsCreateAttribute().CreateClassFile("c:\\Demo\\8", "Models"); + + + //Use Razor Template + //db.DbFirst.UseRazorAnalysis(RazorFirst.DefaultRazorClassTemplate).CreateClassFile(""); + + Console.WriteLine("#### DbFirst End ####"); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/DemoE_CodeFirst.cs b/Src/Asp.Net/DmTest/Demo/DemoE_CodeFirst.cs new file mode 100644 index 000000000..cea14d83b --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/DemoE_CodeFirst.cs @@ -0,0 +1,40 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + public class DemoE_CodeFirst + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### CodeFirst Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString3, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true + }); + // db.DbMaintenance.CreateDatabase(); + db.CodeFirst.InitTables(typeof(CodeFirstTable1));//Create CodeFirstTable1 + db.Insertable(new CodeFirstTable1() { Name = "a", Text="a" }).ExecuteCommand(); + var list = db.Queryable().ToList(); + Console.WriteLine("#### CodeFirst end ####"); + } + } + + public class CodeFirstTable1 + { + [SugarColumn(IsIdentity = true, IsPrimaryKey = true)] + public int Id { get; set; } + public string Name { get; set; } + [SugarColumn(ColumnDataType = "varchar(255)")]//custom + public string Text { get; set; } + [SugarColumn(IsNullable = true)] + public DateTime CreateTime { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/DemoF_Utilities.cs b/Src/Asp.Net/DmTest/Demo/DemoF_Utilities.cs new file mode 100644 index 000000000..0bc041963 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/DemoF_Utilities.cs @@ -0,0 +1,46 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoF_Utilities + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Utilities Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + + List ids = Enumerable.Range(1, 100).ToList(); + db.Utilities.PageEach(ids, 10, list => + { + Console.WriteLine(string.Join("," ,list)); + }); + + var list2= db.Utilities.DataTableToList(db.Ado.GetDataTable("select * from \"ORDER\"")); + + //more https://github.com/sunkaixuan/SqlSugar/wiki/f.Utilities + Console.WriteLine("#### Utilities End ####"); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/DemoG_SimpleClient.cs b/Src/Asp.Net/DmTest/Demo/DemoG_SimpleClient.cs new file mode 100644 index 000000000..cbd6f6036 --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/DemoG_SimpleClient.cs @@ -0,0 +1,36 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoG_SimpleClient + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### SimpleClient Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + Console.WriteLine("#### SimpleClient End ####"); + } + } +} diff --git a/Src/Asp.Net/DmTest/Demo/Democ_GobalFilter.cs b/Src/Asp.Net/DmTest/Demo/Democ_GobalFilter.cs new file mode 100644 index 000000000..f0c8e89ee --- /dev/null +++ b/Src/Asp.Net/DmTest/Demo/Democ_GobalFilter.cs @@ -0,0 +1,77 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + public class DemoC_GobalFilter + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Filter Start ####"); + var db = GetInstance(); + + + var sql = db.Queryable().ToSql(); + //SELECT [Id],[Name],[Price],[CreateTime] FROM `order` WHERE isDelete=0 + Console.WriteLine(sql); + + + var sql2 = db.Queryable((main,ot)=> main.Id==ot.OrderId).ToSql(); + //SELECT [Id],[Name],[Price],[CreateTime] FROM `order` main ,[OrderDetail] ot WHERE ( [main].[Id] = [ot].[OrderId] ) AND main.isDelete=0 + Console.WriteLine(sql2); + + + var sql3 = db.Queryable().Filter("Myfilter").ToSql();// Myfilter+Gobal + //SELECT [Id],[Name],[Price],[CreateTime] FROM `order` WHERE Name='jack' AND isDelete=0 + Console.WriteLine(sql3); + + var sql4 = db.Queryable().Filter("Myfilter",isDisabledGobalFilter:true).ToSql();//only Myfilter + //SELECT [Id],[Name],[Price],[CreateTime] FROM `order` WHERE Name='jack' + Console.WriteLine(sql4); + Console.WriteLine("#### Filter End ####"); + } + + + public static SqlSugarClient GetInstance() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { DbType = DbType.Dm, ConnectionString = Config.ConnectionString, IsAutoCloseConnection = true }); + + //single table query gobal filter + db.QueryFilter.Add(new SqlFilterItem() + { + FilterValue = filterDb => + { + //Writable logic + return new SqlFilterResult() { Sql = " isDelete=0" };//Global string perform best + } + }); + + //Multi-table query gobal filter + db.QueryFilter.Add(new SqlFilterItem() + { + FilterValue = filterDb => + { + //Writable logic + return new SqlFilterResult() { Sql = " main.isDelete=0" }; + }, + IsJoinQuery=true + }); + + //Specific filters + db.QueryFilter.Add(new SqlFilterItem() + { + FilterName= "Myfilter", + FilterValue = filterDb => + { + //Writable logic + return new SqlFilterResult() { Sql = "Name='jack'" }; + } + }); + return db; + } + } +} diff --git a/Src/Asp.Net/DmTest/DmTest.csproj b/Src/Asp.Net/DmTest/DmTest.csproj new file mode 100644 index 000000000..34b0c90ae --- /dev/null +++ b/Src/Asp.Net/DmTest/DmTest.csproj @@ -0,0 +1,101 @@ + + + + + Debug + AnyCPU + {68A45CBA-AD64-429C-9AF4-FE78658B73D5} + Exe + DmTest + DmTest + v4.5 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {489bb790-226c-4fad-8d1e-51d72a7ff8e5} + SqlSugar + + + + \ No newline at end of file diff --git a/Src/Asp.Net/DmTest/Models/AttributeTable.cs b/Src/Asp.Net/DmTest/Models/AttributeTable.cs new file mode 100644 index 000000000..c1a43ad12 --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/AttributeTable.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + [Table("MyAttributeTable")] + //[SugarTable("CustomAttributeTable")] + public class AttributeTable + { + + [Key] + //[SugarColumn(IsPrimaryKey =true)] + public string Id { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/Models/CarType.cs b/Src/Asp.Net/DmTest/Models/CarType.cs new file mode 100644 index 000000000..00dc12710 --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/CarType.cs @@ -0,0 +1,7 @@ +namespace OrmTest +{ + public class CarType + { + public bool State { get; set; } + } +} \ No newline at end of file diff --git a/Src/Asp.Net/DmTest/Models/Custom.cs b/Src/Asp.Net/DmTest/Models/Custom.cs new file mode 100644 index 000000000..3b8871c57 --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/Custom.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Custom + { + public int Id { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/Models/EntityMapper.cs b/Src/Asp.Net/DmTest/Models/EntityMapper.cs new file mode 100644 index 000000000..b597012fb --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/EntityMapper.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SqlSugar; +namespace OrmTest +{ + [SugarTable("MyEntityMapper")] + public class EntityMapper + { + [SugarColumn(ColumnName ="MyName")] + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/Models/Mapper.cs b/Src/Asp.Net/DmTest/Models/Mapper.cs new file mode 100644 index 000000000..8d7991d6c --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/Mapper.cs @@ -0,0 +1,54 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + [SugarTable("OrderDetail")] + public class OrderItemInfo + { + [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int ItemId { get; set; } + public int OrderId { get; set; } + public decimal? Price { get; set; } + [SqlSugar.SugarColumn(IsNullable = true)] + public DateTime? CreateTime { get; set; } + [SugarColumn(IsIgnore = true)] + public Order Order { get; set; } + } + [SugarTable("Order")] + public class OrderInfo + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + public string Name { get; set; } + [SugarColumn(IsIgnore = true)] + public List Items { get; set; } + } + public class ABMapping + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int AId { get; set; } + public int BId { get; set; } + [SugarColumn(IsIgnore = true)] + public A A { get; set; } + [SugarColumn(IsIgnore = true)] + public B B { get; set; } + + } + public class A + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + public string Name { get; set; } + } + public class B + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/Models/MyCustomAttributeTable.cs b/Src/Asp.Net/DmTest/Models/MyCustomAttributeTable.cs new file mode 100644 index 000000000..11359d062 --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/MyCustomAttributeTable.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + [Table("CustomAttributeTable")] + //[SugarTable("CustomAttributeTable")] + public class MyCustomAttributeTable + { + + [Key] + //[SugarColumn(IsPrimaryKey =true)] + public string Id { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/Models/Order.cs b/Src/Asp.Net/DmTest/Models/Order.cs new file mode 100644 index 000000000..d7ff068b8 --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/Order.cs @@ -0,0 +1,24 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + + public class Order + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + + public string Name { get; set; } + public decimal Price { get; set; } + [SugarColumn(IsNullable = true)] + public DateTime CreateTime { get; set; } + [SugarColumn(IsNullable =true)] + public int CustomId { get; set; } + [SugarColumn(IsIgnore = true)] + public List Items { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/Models/OrderItem.cs b/Src/Asp.Net/DmTest/Models/OrderItem.cs new file mode 100644 index 000000000..ae3262c7c --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/OrderItem.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + [SqlSugar.SugarTable("OrderDetail")] + public class OrderItem + { + [SqlSugar.SugarColumn(IsPrimaryKey =true, IsIdentity =true)] + public int ItemId { get; set; } + public int OrderId { get; set; } + public decimal? Price { get; set; } + [SqlSugar.SugarColumn(IsNullable = true)] + public DateTime? CreateTime { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/Models/Student.cs b/Src/Asp.Net/DmTest/Models/Student.cs new file mode 100644 index 000000000..1cee79460 --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/Student.cs @@ -0,0 +1,7 @@ +namespace OrmTest +{ + public class Student + { + public int Id { get; set; } + } +} \ No newline at end of file diff --git a/Src/Asp.Net/DmTest/Models/TestTree.cs b/Src/Asp.Net/DmTest/Models/TestTree.cs new file mode 100644 index 000000000..b8250828a --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/TestTree.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class TestTree + { + [SqlSugar.SugarColumn(ColumnDataType = "hierarchyid")] + public string TreeId { get; set; } + [SqlSugar.SugarColumn(ColumnDataType = "Geography")] + public string GId { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/Models/Tree.cs b/Src/Asp.Net/DmTest/Models/Tree.cs new file mode 100644 index 000000000..d2878de64 --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/Tree.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Tree + { + [SqlSugar.SugarColumn(IsPrimaryKey =true)] + public int Id { get; set; } + public string Name { get; set; } + public int ParentId { get; set; } + [SqlSugar.SugarColumn(IsIgnore = true)] + public Tree Parent { get; set; } + [SqlSugar.SugarColumn(IsIgnore = true)] + public List Child { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/Models/ViewOrder.cs b/Src/Asp.Net/DmTest/Models/ViewOrder.cs new file mode 100644 index 000000000..fcd465747 --- /dev/null +++ b/Src/Asp.Net/DmTest/Models/ViewOrder.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class ViewOrder:Order + { + public string CustomName { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/Program.cs b/Src/Asp.Net/DmTest/Program.cs new file mode 100644 index 000000000..72832d0a2 --- /dev/null +++ b/Src/Asp.Net/DmTest/Program.cs @@ -0,0 +1,40 @@ +using System; + +namespace OrmTest +{ + class Program + { + static void Main(string[] args) + { + //Demo + Demo0_SqlSugarClient.Init(); + Demo1_Queryable.Init(); + Demo2_Updateable.Init(); + Demo3_Insertable.Init(); + Demo4_Deleteable.Init(); + Demo5_SqlQueryable.Init(); + Demo6_Queue.Init(); + Demo7_Ado.Init(); + Demo8_Saveable.Init(); + Demo9_EntityMain.Init(); + DemoA_DbMain.Init(); + DemoB_Aop.Init(); + DemoC_GobalFilter.Init(); + DemoD_DbFirst.Init(); ; + DemoE_CodeFirst.Init(); + DemoF_Utilities.Init(); + DemoG_SimpleClient.Init(); + + //Unit test + //NewUnitTest.Init(); + + //Rest Data + NewUnitTest.RestData(); + + Console.WriteLine("all successfully."); + Console.ReadKey(); + } + + + } +} diff --git a/Src/Asp.Net/DmTest/Properties/AssemblyInfo.cs b/Src/Asp.Net/DmTest/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..61ddd725d --- /dev/null +++ b/Src/Asp.Net/DmTest/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DmTest")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DmTest")] +[assembly: AssemblyCopyright("Copyright © 2020")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("68a45cba-ad64-429c-9af4-fe78658b73d5")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Src/Asp.Net/DmTest/UnitTest/Main.cs b/Src/Asp.Net/DmTest/UnitTest/Main.cs new file mode 100644 index 000000000..0c39ced0e --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/Main.cs @@ -0,0 +1,46 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + public partial class NewUnitTest + { + public static SqlSugarClient Db=> new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + public static void RestData() + { + Db.Deleteable().ExecuteCommand(); + Db.Deleteable().ExecuteCommand(); + } + public static void Init() + { + Save(); + CodeFirst(); + Updateable(); + Json(); + Ado(); + Queryable(); + QueryableAsync(); + Thread(); + Thread2(); + Thread3(); + } + } +} diff --git a/Src/Asp.Net/DmTest/UnitTest/UAdo.cs b/Src/Asp.Net/DmTest/UnitTest/UAdo.cs new file mode 100644 index 000000000..49788f35a --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/UAdo.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public partial class NewUnitTest + { + public static void Ado() + { + + var task1 = Db.Ado.GetScalarAsync("select 1"); + task1.Wait(); + UValidate.Check(1, task1.Result, "ado"); + + var task2 = Db.Ado.GetIntAsync("select 2"); + task2.Wait(); + UValidate.Check(2, task2.Result, "ado"); + + + var task3 = Db.Ado.GetLongAsync("select 3"); + task3.Wait(); + UValidate.Check(3, task3.Result, "ado"); + + + var task4 = Db.Ado.GetDataTableAsync("select 4 as id"); + task4.Wait(); + UValidate.Check(4, task4.Result.Rows[0]["id"], "ado"); + + + var task5 = Db.Ado.GetInt("select @id as id",new { id=5}); + UValidate.Check(5, task5, "ado"); + + + + var task6 = Db.Ado.SqlQuery("select @id as id", new { id = 5 }); + UValidate.Check(5, task6[0].id, "ado"); + + + var task7 = Db.Ado.SqlQueryAsync("select @id as id", new { id = 7 }); + task7.Wait(); + UValidate.Check(7, task7.Result[0].id, "ado"); + + + var task8 = Db.Ado.SqlQueryAsync("select 8 as id"); + task8.Wait(); + UValidate.Check(8, task8.Result[0].id, "ado"); + + var task9=Db.Ado.SqlQuery(@"select * from ""order"";select * from OrderDetail"); + + var task10 = Db.Ado.SqlQueryAsync(@"select * from ""order"";select * from OrderDetail"); + task10.Wait(); + } + } +} diff --git a/Src/Asp.Net/DmTest/UnitTest/UCodeFirst.cs b/Src/Asp.Net/DmTest/UnitTest/UCodeFirst.cs new file mode 100644 index 000000000..099832be8 --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/UCodeFirst.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public partial class NewUnitTest + { + public static void CodeFirst() + { + if (Db.DbMaintenance.IsAnyTable("UnitCodeTest1", false)) + Db.DbMaintenance.DropTable("UnitCodeTest1"); + Db.CodeFirst.InitTables(); + } + public class UnitCodeTest1 + { + [SqlSugar.SugarColumn(IndexGroupNameList = new string[] { "group1" })] + public int Id { get; set; } + [SqlSugar.SugarColumn(DefaultValue= "now()", IndexGroupNameList =new string[] {"group1" } )] + public DateTime? CreateDate { get; set; } + } + } +} diff --git a/Src/Asp.Net/DmTest/UnitTest/UJson.cs b/Src/Asp.Net/DmTest/UnitTest/UJson.cs new file mode 100644 index 000000000..a7fd05df8 --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/UJson.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public partial class NewUnitTest + { + + public static void Json() + { + Db.CodeFirst.InitTables(); + Db.DbMaintenance.TruncateTable(); + Db.Insertable(new UnitJsonTest() { Order = new Order { Id = 1, Name = "order1" } }).ExecuteCommand(); + var list = Db.Queryable().ToList(); + UValidate.Check("order1", list.First().Order.Name, "Json"); + Db.Updateable(new UnitJsonTest() { Id = Db.Queryable().First().Id, Order = new Order { Id = 2, Name = "order2" } }).ExecuteCommand(); + list= Db.Queryable().ToList(); + UValidate.Check("order2", list.First().Order.Name, "Json"); + var list2 = Db.Queryable().ToList(); + } + } + + + public class UnitJsonTest + { + [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + [SqlSugar.SugarColumn(ColumnDataType = "varchar(4000)", IsJson = true)] + public Order Order { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/UnitTest/UQueryable.cs b/Src/Asp.Net/DmTest/UnitTest/UQueryable.cs new file mode 100644 index 000000000..9fdc0766d --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/UQueryable.cs @@ -0,0 +1,323 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public partial class NewUnitTest + { + public static void Queryable() + { + + var pageindex = 1; + var pagesize = 10; + var total = 0; + var totalPage = 0; + var list = Db.Queryable().ToPageList(pageindex, pagesize, ref total, ref totalPage); + + //Db.CodeFirst.InitTables(typeof(CarType)); + //Db.Updateable() + // .SetColumns(it => new CarType { State = SqlSugar.SqlFunc.IIF(it.State == true, false, true) }).Where(it => true) + // .ExecuteCommand(); + + //Db.CodeFirst.InitTables(typeof(TestTree)); + //Db.DbMaintenance.TruncateTable(); + //Db.Ado.ExecuteCommand("insert testtree values(hierarchyid::GetRoot(),geography :: STGeomFromText ('POINT(55.9271035250276 -3.29431266523898)',4326),'name')"); + //var list2 = Db.Queryable().ToList(); + + Db.CodeFirst.InitTables(); + Db.Queryable().Where(it => it.Id.HasValue).ToList(); + + Db.Queryable().Where(it => SqlSugar.SqlFunc.Equals(it.CreateTime.Date, it.CreateTime.Date)).ToList(); + + var sql = Db.Queryable().Select(it => new UnitSelectTest() + { + + DcNull = it.Dc, + Dc = it.Int + }).ToSql().Key; + UValidate.Check(sql, "SELECT \"dc\" AS \"dcnull\" , \"int\" AS \"dc\" FROM \"unitselecttest\"", "Queryable"); + + sql = Db.Updateable(new UnitSelectTest2()).ToSql().Key; + UValidate.Check(sql, @"UPDATE ""unitselecttest2"" SET + ""dc""=@Dc,""intnull""=@IntNull WHERE ""int""=@Int", "Queryable"); + + sql = Db.Queryable().IgnoreColumns(it => it.CreateTime).ToSql().Key; + UValidate.Check(sql, "SELECT \"id\",\"name\",\"price\",\"customid\" FROM \"order\" ", "Queryable"); + sql = Db.Queryable().IgnoreColumns(it => new { it.Id, it.Name }).ToSql().Key; + UValidate.Check(sql, "SELECT \"price\",\"createtime\",\"customid\" FROM \"order\" ", "Queryable"); + sql = Db.Queryable().IgnoreColumns("id").ToSql().Key; + UValidate.Check(sql, "SELECT \"name\",\"price\",\"createtime\",\"customid\" FROM \"order\" ", "Queryable"); + + var cts = IEnumerbleContains.Data(); + var list2=Db.Queryable() + .Where(p => /*ids.*/cts.Select(c => c.Id).Contains(p.Id)).ToList(); + + var cts2 = IEnumerbleContains.Data().ToList(); ; + var list3 = Db.Queryable() + .Where(p => /*ids.*/cts2.Select(c => c.Id).Contains(p.Id)).ToList(); + + + var list4 = Db.Queryable() + .Where(p => new List { 1, 2, 3 }.Where(b => b > 1).Contains(p.Id)).ToList(); + + Db.CodeFirst.InitTables(); + var list5 = Db.Queryable().Where(it => SqlSugar.SqlFunc.ToString(it.Date.Value.Year) == "1").ToList(); + var list6 = Db.Queryable().Where(it => it.Date.Value.Year == 1).ToList(); + var list7 = Db.Queryable().Where(it => it.Date.Value.Date == DateTime.Now.Date).ToList(); + + + SaleOrder saleOrderInfo = new SaleOrder(); + Db.CodeFirst.InitTables(); + var result = Db.GetSimpleClient().Update(o => new SaleOrder() + { + OrderStatus = 1, + CheckMan = saleOrderInfo.CheckMan, + CheckTime = DateTime.Now + }, o => o.OrderSn == saleOrderInfo.OrderSn && o.OrderStatus != 1); + } + + public static class IEnumerbleContains + { + public static IEnumerable Data() + { + for (int i = 0; i < 100; i++) + { + yield return new Order + { + Id = i, + }; + } + } + } + [SugarTable("UnitSaleOrder")] + public class SaleOrder + { + public SaleOrder() + { + SaleDate = DateTime.Now; + Team = 1; + AddTime = DateTime.Now; + OrderStatus = 0; + Points = 0; + PayPoints = 0; + PointsExchangeMoney = decimal.Zero; + IsPushMessage = false; + CostAmount = decimal.Zero; + OrderAmount = decimal.Zero; + RealOrderAmount = decimal.Zero; + AccountsDueAmount = decimal.Zero; + SettleType = 0; + IsPushMessage = false; + } + + /// + /// 订单号 + /// + public string OrderSn { get; set; } + + /// + /// 客户编号 + /// + public string CustomerNo { get; set; } + + + /// + /// 收货人姓名 + /// + public string CustomerName { get; set; } + + /// + /// 成本总金额 + /// + public decimal CostAmount { get; set; } + + /// + /// 订单总金额 + /// + public decimal OrderAmount { get; set; } + + /// + /// 实收金额(整单优惠后) + /// + public decimal RealOrderAmount { get; set; } + + /// + /// 销货日期 + /// + public DateTime SaleDate { get; set; } + + /// + /// 下单时间 + /// + public DateTime AddTime { get; set; } + + /// + /// 媒体资源投放ID + /// + public string IndustryCode { get; set; } + + public string IndustryName { get; set; } + + /// + /// 备注 + /// + public string Remark { get; set; } + + /// + /// 班组 + /// + public int Team { get; set; } + + /// + /// 销售员编号 + /// + public string SellerNo { get; set; } + + /// + /// 销售员姓名 + /// + public string SellerName { get; set; } + + /// + /// 操作人ID + /// + public virtual string HandlerCode { get; set; } + + /// + /// 操作者 + /// + public string Handler { get; set; } + + /// + /// 发货仓库代号 + /// + public string StoreCode { get; set; } + + /// + /// 发货仓库名称 + /// + public string StoreName { get; set; } + + /// + /// 销货店铺渠道代号 + /// + public string ShopChannelCode { get; set; } + + /// + /// 销货店铺渠道名称 + /// + public string ShopChannelName { get; set; } + + /// + /// 订单产品数 + /// + public int GoodsNum { get; set; } + + /// + /// 礼品数量 + /// + public int GiftNum { get; set; } + + /// + /// 对应预订单号 + /// + public string CustomerOrderSn { get; set; } + + /// + /// 订单赠送积分 + /// + public int Points { get; set; } + + /// + /// 应收款金额 + /// + public decimal AccountsDueAmount { get; set; } + + /// + /// 来自预约单号 + /// + public string ReserationOrderSn { get; set; } + + + /// + /// 订单状态 0为未审核 1为已审核 + /// + public int OrderStatus { get; set; } + + /// + /// 审核人 + /// + public string CheckMan { get; set; } + + /// + /// 审核时间 + /// + public DateTime? CheckTime { get; set; } + + /// + /// 结算类型 0为非金工石(零售) 1为金工石 + /// + public int SettleType { get; set; } + + /// + /// 使用积分 + /// + public int PayPoints { get; set; } + + /// + /// 积分抵现金额 + /// + public decimal PointsExchangeMoney { get; set; } + + /// + /// 是否已推送微信消息 + /// + public bool IsPushMessage { get; set; } + + } + + public class SaleOrderBaseInfo + { + public int GoodsNum { get; set; } + + public int GiftNum { get; set; } + + public decimal OrderAmount { get; set; } + + } + + + public class UnitTest3 + { + public DateTime? Date { get; set; } + } + + + public class UnitSelectTest2 + { + [SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)] + public decimal? DcNull { get; set; } + public decimal Dc { get; set; } + public int? IntNull { get; set; } + [SqlSugar.SugarColumn(IsPrimaryKey = true)] + public decimal Int { get; set; } + } + + public class UnitSelectTest + { + public decimal? DcNull { get; set; } + public decimal Dc { get; set; } + public int? IntNull { get; set; } + public decimal Int { get; set; } + } + + public class UnitGuidTable + { + public Guid? Id { get; set; } + } + } +} diff --git a/Src/Asp.Net/DmTest/UnitTest/UQueryableAsync.cs b/Src/Asp.Net/DmTest/UnitTest/UQueryableAsync.cs new file mode 100644 index 000000000..7ebce71e8 --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/UQueryableAsync.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SqlSugar; +namespace OrmTest +{ + public partial class NewUnitTest + { + public static void QueryableAsync() + { + q1(); + q2(); + q3(); + } + + private static void q1() + { + RefAsync total = 0; + var count = Db.Queryable().Count(); + Task t = Db.Queryable().ToPageListAsync(1, 2, total); + t.Wait(); + UValidate.Check(count, total.Value, "QueryableAsync"); + } + private static void q2() + { + RefAsync total = 0; + var count = Db.Queryable().Count(); + Task t = Db.Queryable().ToDataTablePageAsync(1, 2, total); + t.Wait(); + UValidate.Check(count, total.Value, "QueryableAsync"); + } + private static void q3() + { + RefAsync total = 0; + var count = Db.Queryable().Count(); + Task t = Db.Queryable().ToJsonPageAsync(1, 2, total); + t.Wait(); + UValidate.Check(count, total.Value, "QueryableAsync"); + } + } +} diff --git a/Src/Asp.Net/DmTest/UnitTest/USave.cs b/Src/Asp.Net/DmTest/UnitTest/USave.cs new file mode 100644 index 000000000..98a05561d --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/USave.cs @@ -0,0 +1,95 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public partial class NewUnitTest + { + public static void Save() + { + Db.CodeFirst.InitTables(); + Db.DbMaintenance.TruncateTable(); + Db.Saveable(new UnitSysMenu() { ID="aa", ButtonList="", CreateName="a", CreateTime=DateTime.Now, ImageUrl="", IsDel=true, MenuCode="a", NavigateUrl="a", UpdateName="", Remark="", UpdateTime=DateTime.Now }).ExecuteReturnEntity(); + } + } + public class BaseEntity + { + /// + /// ID + /// + [SugarColumn(IsPrimaryKey = true, ColumnDescription = "ID", Length = 32)] + public string ID { get; set; } + /// + /// 删除标记 + /// + [ SugarColumn(ColumnDescription = "删除标记")] + public bool IsDel { get; set; } + /// + /// 排序字段 + /// + [SugarColumn(ColumnDescription = "排序字段", IsIdentity = true)] + public int SortIndex { get; set; } + /// + /// 添加操作员 + /// + [ SugarColumn(ColumnDescription = "添加操作员", Length = 10, IsNullable = true)] + public string CreateName { get; set; } + /// + /// 添加时间 + /// + [ SugarColumn(ColumnDescription = "添加时间", IsNullable = true)] + public DateTime? CreateTime { get; set; } + /// + /// 修改操作员 + /// + [ SugarColumn(ColumnDescription = "修改操作员", Length = 10, IsNullable = true)] + public string UpdateName { get; set; } + /// + /// 修改时间 + /// + [ SugarColumn(ColumnDescription = "修改时间", IsNullable = true)] + public DateTime? UpdateTime { get; set; } + /// + /// 备注 + /// + [SugarColumn(ColumnDescription = "备注", Length = 150, IsNullable = true)] + public string Remark { get; set; } + } + public class UnitSysMenu : BaseEntity + { + public UnitSysMenu() + { + } + /// + /// 菜单图标 + /// + [SqlSugar.SugarColumn(Length = 150, ColumnDescription = "菜单图标")] + + public string ImageUrl { get; set; } + /// + /// 菜单编码 + /// + [SqlSugar.SugarColumn(Length = 50, ColumnDescription = "菜单编码")] + public string MenuCode { get; set; } + /// + /// 菜单地址 + /// + [ SqlSugar.SugarColumn(Length = 200, IsNullable = true, ColumnDescription = "菜单地址")] + public string NavigateUrl { get; set; } + /// + /// 菜单功能 + /// + [SqlSugar.SugarColumn(IsIgnore = true)] + public string ButtonList { get; set; } + + /// + /// 排序字段 + /// + [SugarColumn(ColumnDescription = "排序字段", IsIdentity = true)] + public int SortIndex { get; set; } + } +} diff --git a/Src/Asp.Net/DmTest/UnitTest/UThread.cs b/Src/Asp.Net/DmTest/UnitTest/UThread.cs new file mode 100644 index 000000000..76b653667 --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/UThread.cs @@ -0,0 +1,378 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public partial class NewUnitTest + { + + public static SqlSugarClient simpleDb => new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + public static SqlSugarClient ssDb => new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + IsShardSameThread = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + public static SqlSugarClient singleDb = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + public static SqlSugarClient singleAndSsDb = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.Dm, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + IsShardSameThread = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + public static void Thread() + { + Simple(); + IsShardSameThread(); + Single(); + SingleAndIsShardSameThread(); + SimpleAsync(); + IsShardSameThreadAsync(); + SingleAsync(); + SingleAndIsShardSameThreadAsync(); + + } + + private static void Simple() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void SingleAndIsShardSameThread() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleAndSsDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleAndSsDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleAndSsDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void Single() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void IsShardSameThread() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + Db.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + Db.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + Db.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommand(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + + + private static void SimpleAsync() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); ; + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void SingleAndIsShardSameThreadAsync() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleAndSsDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleAndSsDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleAndSsDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void SingleAsync() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + singleDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void IsShardSameThreadAsync() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + Db.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + Db.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + Db.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + } +} diff --git a/Src/Asp.Net/DmTest/UnitTest/UThread2.cs b/Src/Asp.Net/DmTest/UnitTest/UThread2.cs new file mode 100644 index 000000000..5fe4c12dd --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/UThread2.cs @@ -0,0 +1,316 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public partial class NewUnitTest + { + + public static void Thread2() + { + Simple2(); + IsShardSameThread2(); + Single2(); + SingleAndIsShardSameThread2(); + SimpleAsync2(); + IsShardSameThreadAsync2(); + SingleAsync2(); + SingleAndIsShardSameThreadAsync2(); + + } + + private static void Simple2() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void SingleAndIsShardSameThread2() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void Single2() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void IsShardSameThread2() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToList(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + + + private static void SimpleAsync2() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); ; + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void SingleAndIsShardSameThreadAsync2() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void SingleAsync2() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + + private static void IsShardSameThreadAsync2() + { + var t1 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); + System.Threading.Thread.Sleep(1); + } + + }); + var t2 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); + System.Threading.Thread.Sleep(10); + } + + }); + var t3 = new Task(() => + { + for (int i = 0; i < 100; i++) + { + simpleDb.Queryable().Take(10).ToListAsync().Wait(); + System.Threading.Thread.Sleep(6); + } + + }); + t1.Start(); + t2.Start(); + t3.Start(); + + Task.WaitAll(t1, t2, t3); + } + } +} diff --git a/Src/Asp.Net/DmTest/UnitTest/UThread3.cs b/Src/Asp.Net/DmTest/UnitTest/UThread3.cs new file mode 100644 index 000000000..9e0e644c4 --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/UThread3.cs @@ -0,0 +1,117 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public partial class NewUnitTest + { + + public static void Thread3() + { + Console.WriteLine("Thread3"); + SimpleAsync3().Wait(); + IsShardSameThreadAsync3().Wait(); + SingleAsync3().Wait(); + SingleAndIsShardSameThreadAsync3().Wait(); + + } + + + + private static async Task SimpleAsync3() + { + + for (int i = 0; i < 100; i++) + { + await simpleDb.Queryable().Take(10).ToListAsync(); + } + + for (int i = 0; i < 100; i++) + { + await simpleDb.Insertable(new Order() { Name = "a", CustomId = 1 }).ExecuteCommandAsync(); + } + + List orders = new List(); + for (int i = 0; i < 100; i++) + { + orders = await simpleDb.Queryable().Take(10).ToListAsync(); + } + if (orders.Count > 0) + { + Console.WriteLine("async is ok"); + } + } + + private static async Task SingleAndIsShardSameThreadAsync3() + { + for (int i = 0; i < 100; i++) + { + await singleAndSsDb.Queryable().Take(10).ToListAsync(); + } + + for (int i = 0; i < 100; i++) + { + await singleAndSsDb.Insertable(new Order() { Name = "a", CustomId = 1 }).ExecuteCommandAsync(); + } + List orders = new List(); + for (int i = 0; i < 100; i++) + { + orders = await singleAndSsDb.Queryable().Take(10).ToListAsync(); + } + if (orders.Count > 0) + { + Console.WriteLine("async is ok"); + } + } + + private static async Task SingleAsync3() + { + for (int i = 0; i < 100; i++) + { + await singleDb.Queryable().Take(10).ToListAsync(); + } + + for (int i = 0; i < 100; i++) + { + await singleDb.Insertable(new Order() { Name = "a", CustomId = 1 }).ExecuteCommandAsync(); + } + + List orders = new List(); + for (int i = 0; i < 100; i++) + { + orders = await singleDb.Queryable().Take(10).ToListAsync(); + } + if (orders.Count > 0) + { + Console.WriteLine("async is ok"); + } + } + + private static async Task IsShardSameThreadAsync3() + { + for (int i = 0; i < 100; i++) + { + await ssDb.Queryable().Take(10).ToListAsync(); + } + + for (int i = 0; i < 100; i++) + { + await ssDb.Insertable(new Order() { Name = "a", CustomId = 1 }).ExecuteCommandAsync(); + } + + List orders = new List(); + for (int i = 0; i < 100; i++) + { + orders = await ssDb.Queryable().Take(10).ToListAsync(); + } + if (orders.Count > 0) + { + Console.WriteLine("async is ok"); + } + } + } +} diff --git a/Src/Asp.Net/DmTest/UnitTest/UValidate.cs b/Src/Asp.Net/DmTest/UnitTest/UValidate.cs new file mode 100644 index 000000000..bc2b97fc2 --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/UValidate.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class UValidate + { + public static void Check(object a, object b, object name) + { + if (a?.ToString()?.Trim() != b?.ToString()?.Trim()) + { + throw new Exception(name + " error"); + } + } + } +} diff --git a/Src/Asp.Net/DmTest/UnitTest/Updateable.cs b/Src/Asp.Net/DmTest/UnitTest/Updateable.cs new file mode 100644 index 000000000..3c2863c90 --- /dev/null +++ b/Src/Asp.Net/DmTest/UnitTest/Updateable.cs @@ -0,0 +1,211 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public partial class NewUnitTest + { + public static void Updateable() + { + Db.CodeFirst.InitTables(typeof(UnitUser)); + Db.DbMaintenance.TruncateTable(); + Db.Insertable(new UnitUser() { USER_ID=1,USER_ACCOUNT = "a", USER_PWD = "b", USER_NAME = "c", PWD_LASTCHTIME = DateTime.Now, PWD_ERRORCOUNT = 1, PWD_LASTERRTIME = DateTime.Now }).ExecuteCommand(); + Db.Updateable(new UnitUser() { USER_ID=1, PWD_LASTERRTIME = null }).WhereColumns(it=> new{ it.PWD_ERRORCOUNT, it.PWD_LASTERRTIME }).ExecuteCommand(); + Db.CodeFirst.InitTables(typeof(UnitBoolTest)); + var x = new UnitBoolTest(); + //Db.Updateable().SetColumns(it => new UnitBoolTest() { BoolValue = !it.BoolValue }).Where(it=>it.Id==1).ExecuteCommand(); + //Db.Updateable().SetColumns(it => it.BoolValue == !it.BoolValue ).Where(it=>it.Id==1).ExecuteCommand(); + Db.Updateable().SetColumns(it => new UnitBoolTest() { BoolValue = x.BoolValue }).Where(it => it.Id == 1).ExecuteCommand(); + Db.Updateable().SetColumns(it => it.BoolValue == x.BoolValue).Where(it => it.Id == 1).ExecuteCommand(); + Db.Updateable().SetColumns(it => new UnitBoolTest() { BoolValue = !x.BoolValue }).Where(it => it.Id == 1).ExecuteCommand(); + //Db.Updateable().SetColumns(it => it.BoolValue == !x.BoolValue).Where(it => it.Id == 1).ExecuteCommand(); + Db.Updateable(x).ReSetValue(it => it.BoolValue == it.BoolValue).ExecuteCommand(); + Db.Updateable(x).ReSetValue(it => it.BoolValue == true).ExecuteCommand(); + //Db.Updateable(x).ReSetValue(it => it.BoolValue == !it.BoolValue).ExecuteCommand(); + Db.Updateable(x).UpdateColumns(it =>new { it.BoolValue }) .ExecuteCommand(); + + + + UnitSaveDiary saveDiary = new UnitSaveDiary(); + saveDiary.ID = 2; + saveDiary.TypeID = 10; + saveDiary.TypeName = "类型100"; + saveDiary.Title = "标题1000"; + saveDiary.Content = "内容"; + saveDiary.Time = DateTime.Now; + saveDiary.IsRemind = false;//无论传false/true 最终执行的结果都是以true执行的 + + var sql = Db.Updateable().SetColumns(it => new UnitDiary() + { + IsRemind = saveDiary.IsRemind, + }).Where(it => it.ID == saveDiary.ID).ToSql(); + UValidate.Check(sql.Key, @"UPDATE ""diary"" SET + ""isremind"" = @Const0 WHERE ( ""id"" = @ID1 )", "Updateable"); + + + sql = Db.Updateable().SetColumns(it => new UnitDiary() + { + TypeID = saveDiary.TypeID, + }).Where(it => it.ID == saveDiary.ID).ToSql(); + UValidate.Check(sql.Key, @"UPDATE ""diary"" SET + ""typeid"" = @Const0 WHERE ( ""id"" = @ID1 )", "Updateable"); + + } + } + public class UnitSaveDiary + { + public int ID { get; set; } + public int TypeID { get; set; } + public string TypeName { get; set; } + public string Title { get; set; } + public string Content { get; set; } + public DateTime? Time { get; set; } + public bool IsRemind { get; set; } + } + /// + /// 日记表 + /// + [SugarTable("Diary")] + public class UnitDiary + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int ID { get; set; } + /// + /// 用户ID + /// + public int? UserID { get; set; } + /// + /// 日记类型ID + /// + public int? TypeID { get; set; } + /// + /// 日记类型名称 + /// + public string TypeName { get; set; } + /// + /// 标题 + /// + public string Title { get; set; } + /// + /// 内容 + /// + public string Content { get; set; } + /// + /// 时间 + /// + public DateTime? Time { get; set; } + /// + /// 是否提醒 + /// + public bool? IsRemind { get; set; } + /// + /// 封面图 + /// + public string Cover { get; set; } + /// + /// 是否为系统日记 1:系统日记 0:用户日记 + /// + public bool? IsSystem { get; set; } + /// + /// 权重(排序) + /// + public int? Sequence { get; set; } + /// + /// + /// + public string IP { get; set; } + /// + /// + /// + public DateTime? CreateTime { get; set; } + /// + /// + /// + public DateTime? UpdateTime { get; set; } + /// + /// + /// + public bool? IsDelete { get; set; } + } + + public class UnitBoolTest + { + [SugarColumn(IsPrimaryKey =true)] + public int Id { get; set; } + public bool BoolValue { get; set; } + public string Name { get; set; } + } + /// + /// 普通用户表 + /// + [Serializable] + public class UnitUser + { + private System.Int64? _USER_ID; + /// + /// GUID主键 + /// + [SugarColumn(IsPrimaryKey = true, IsIdentity = false)] + public System.Int64? USER_ID { get { return this._USER_ID; } set { this._USER_ID = value; } } + + private System.String _USER_ACCOUNT; + /// + /// 用户账号,不可重名,即使是假删除了,亦不可重复 + /// + public System.String USER_ACCOUNT { get { return this._USER_ACCOUNT; } set { this._USER_ACCOUNT = value; } } + + private System.String _USER_PWD; + /// + /// 用户密码 + /// + public System.String USER_PWD + { + get { return this._USER_PWD; } + set { this._USER_PWD = value; } + } + /// + /// 不允许用户密码序列化,可以反序列化 + /// + /// + public bool ShouldSerializeUSER_PWD() + { + return false; + } + + private System.String _USER_NAME; + /// + /// 用户姓名 + /// + + public System.String USER_NAME { get { return this._USER_NAME; } set { this._USER_NAME = value; } } + + private System.Int32 _USER_STATUS; + /// + /// 用户状体:10正常;20锁定;99已删除 + /// + public System.Int32 USER_STATUS { get { return this._USER_STATUS; } set { this._USER_STATUS = value; } } + + private System.DateTime _PWD_LASTCHTIME; + /// + /// 最后一次密码更新时间 + /// + public System.DateTime PWD_LASTCHTIME { get { return this._PWD_LASTCHTIME; } set { this._PWD_LASTCHTIME = value; } } + + private System.Int32? _PWD_ERRORCOUNT; + /// + /// 密码错误次数,达到定义的次数就锁定 + /// + public System.Int32? PWD_ERRORCOUNT { get { return this._PWD_ERRORCOUNT; } set { this._PWD_ERRORCOUNT = value ?? 0; } } + + private System.DateTime? _PWD_LASTERRTIME = null; + /// + /// 密码最后一次错误时间,满足定义的时间差之后,可自动解锁,如20分钟后自动解锁,亦作为累次错误次数的时间差比对基础 + /// 允许为空 + /// + public System.DateTime? PWD_LASTERRTIME { get { return this._PWD_LASTERRTIME; } set { this._PWD_LASTERRTIME = value; } } + } +} diff --git a/Src/Asp.Net/SqlSugar.sln b/Src/Asp.Net/SqlSugar.sln index bb5c721eb..7e18c93bf 100644 --- a/Src/Asp.Net/SqlSugar.sln +++ b/Src/Asp.Net/SqlSugar.sln @@ -27,6 +27,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SqlSugar.DbFirstExtensions" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PgSqlTest", "PgSqlTest\PgSqlTest.csproj", "{86A55D46-B5F5-44B4-8B60-2AED1E2EDD99}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DmTest", "DmTest\DmTest.csproj", "{68A45CBA-AD64-429C-9AF4-FE78658B73D5}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -77,6 +79,10 @@ Global {86A55D46-B5F5-44B4-8B60-2AED1E2EDD99}.Debug|Any CPU.Build.0 = Debug|Any CPU {86A55D46-B5F5-44B4-8B60-2AED1E2EDD99}.Release|Any CPU.ActiveCfg = Release|Any CPU {86A55D46-B5F5-44B4-8B60-2AED1E2EDD99}.Release|Any CPU.Build.0 = Release|Any CPU + {68A45CBA-AD64-429C-9AF4-FE78658B73D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {68A45CBA-AD64-429C-9AF4-FE78658B73D5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {68A45CBA-AD64-429C-9AF4-FE78658B73D5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {68A45CBA-AD64-429C-9AF4-FE78658B73D5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Src/Asp.Net/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs b/Src/Asp.Net/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs index 6b38b51f7..4a56aa0b2 100644 --- a/Src/Asp.Net/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs +++ b/Src/Asp.Net/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs @@ -341,6 +341,12 @@ namespace SqlSugar case DbType.PostgreSQL: DependencyManagement.TryPostgreSQL(); break; + case DbType.Kdbndp: + DependencyManagement.TryKdbndb(); + break; + case DbType.Dm: + DependencyManagement.TryDm(); + break; default: throw new Exception("ConnectionConfig.DbType is null"); } diff --git a/Src/Asp.Net/SqlSugar/Enum/DbType.cs b/Src/Asp.Net/SqlSugar/Enum/DbType.cs index 40e040cbf..7765f14c0 100644 --- a/Src/Asp.Net/SqlSugar/Enum/DbType.cs +++ b/Src/Asp.Net/SqlSugar/Enum/DbType.cs @@ -11,6 +11,8 @@ namespace SqlSugar SqlServer, Sqlite, Oracle, - PostgreSQL + PostgreSQL, + Dm, + Kdbndp } } diff --git a/Src/Asp.Net/SqlSugar/ExpressionsToSql/Subquery/Items/SubAnd.cs b/Src/Asp.Net/SqlSugar/ExpressionsToSql/Subquery/Items/SubAnd.cs index b45a3d4ee..74bfbc1d0 100644 --- a/Src/Asp.Net/SqlSugar/ExpressionsToSql/Subquery/Items/SubAnd.cs +++ b/Src/Asp.Net/SqlSugar/ExpressionsToSql/Subquery/Items/SubAnd.cs @@ -49,6 +49,10 @@ namespace SqlSugar { regex = @"^AND (\:Const\d+) $"; } + if (this.Context is DmExpressionContext) + { + regex = @"^AND (\:Const\d+) $"; + } if (Regex.IsMatch(result, regex)) { result = "AND " + this.Context.Parameters.First(it => it.ParameterName == Regex.Match(result, regex).Groups[1].Value).Value; diff --git a/Src/Asp.Net/SqlSugar/ExpressionsToSql/Subquery/Items/SubWhere.cs b/Src/Asp.Net/SqlSugar/ExpressionsToSql/Subquery/Items/SubWhere.cs index 7174e5cfc..e640f6666 100644 --- a/Src/Asp.Net/SqlSugar/ExpressionsToSql/Subquery/Items/SubWhere.cs +++ b/Src/Asp.Net/SqlSugar/ExpressionsToSql/Subquery/Items/SubWhere.cs @@ -49,6 +49,10 @@ namespace SqlSugar { regex = @"^WHERE (\:Const\d+) $"; } + if (this.Context is DmExpressionContext) + { + regex = @"^WHERE (\:Const\d+) $"; + } if (Regex.IsMatch(result, regex)) { result = "WHERE " + this.Context.Parameters.First(it => it.ParameterName == Regex.Match(result, regex).Groups[1].Value).Value; diff --git a/Src/Asp.Net/SqlSugar/Infrastructure/DependencyManagement.cs b/Src/Asp.Net/SqlSugar/Infrastructure/DependencyManagement.cs index f8f6ab2c1..3a8c489ec 100644 --- a/Src/Asp.Net/SqlSugar/Infrastructure/DependencyManagement.cs +++ b/Src/Asp.Net/SqlSugar/Infrastructure/DependencyManagement.cs @@ -13,6 +13,7 @@ namespace SqlSugar private static bool IsTrySqlite = false; private static bool IsTryOracle = false; private static bool IsTryPgSql = false; + private static bool IsTryDm = false; public static void TryJsonNet() { if (!IsTryJsonNet) @@ -110,5 +111,28 @@ namespace SqlSugar } } } + + public static void TryKdbndb() + { + throw new Exception("Kdbndb只能在.NetCore版本下使用"); + } + + public static void TryDm() + { + if (!IsTryDm) + { + try + { + DmProvider db = new DmProvider(); + var conn = db.GetAdapter(); + IsTryDm = true; + } + catch (Exception ex) + { + + throw new Exception("你需要引用DmProvider.dll"); + } + } + } } } diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/CodeFirst/DmSQLCodeFirst.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/CodeFirst/DmCodeFirst.cs similarity index 98% rename from Src/Asp.Net/SqlSugar/Realization/Dm/CodeFirst/DmSQLCodeFirst.cs rename to Src/Asp.Net/SqlSugar/Realization/Dm/CodeFirst/DmCodeFirst.cs index d446243f9..15427e1c9 100644 --- a/Src/Asp.Net/SqlSugar/Realization/Dm/CodeFirst/DmSQLCodeFirst.cs +++ b/Src/Asp.Net/SqlSugar/Realization/Dm/CodeFirst/DmCodeFirst.cs @@ -5,7 +5,7 @@ using System.Text; namespace SqlSugar { - public class DmSQLCodeFirst : CodeFirstProvider + public class DmCodeFirst : CodeFirstProvider { public override void NoExistLogic(EntityInfo entityInfo) { diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/DbBind/DmDbBind.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/DbBind/DmDbBind.cs index 9e8d29576..9927d5d77 100644 --- a/Src/Asp.Net/SqlSugar/Realization/Dm/DbBind/DmDbBind.cs +++ b/Src/Asp.Net/SqlSugar/Realization/Dm/DbBind/DmDbBind.cs @@ -6,20 +6,44 @@ namespace SqlSugar { public class DmDbBind : DbBindProvider { + public override string GetDbTypeName(string csharpTypeName) + { + if (csharpTypeName == UtilConstants.ByteArrayType.Name) + return "blob"; + if (csharpTypeName.ToLower() == "int32") + csharpTypeName = "int"; + if (csharpTypeName.ToLower() == "int16") + csharpTypeName = "short"; + if (csharpTypeName.ToLower() == "int64") + csharpTypeName = "long"; + if (csharpTypeName.ToLower().IsIn("boolean", "bool")) + csharpTypeName = "bool"; + var mappings = this.MappingTypes.Where(it => it.Value.ToString().Equals(csharpTypeName, StringComparison.CurrentCultureIgnoreCase)); + return mappings.HasValue() ? mappings.First().Key : "varchar"; + } public override string GetPropertyTypeName(string dbTypeName) { dbTypeName = dbTypeName.ToLower(); var propertyTypes = MappingTypes.Where(it => it.Value.ToString().ToLower() == dbTypeName || it.Key.ToLower() == dbTypeName); - if (propertyTypes == null) + if (dbTypeName == "int32") + { + return "int"; + } + else if (dbTypeName == "int64") + { + return "long"; + } + else if (dbTypeName == "int16") + { + return "short"; + } + else if (propertyTypes == null) { return "other"; } - else if (dbTypeName == "xml" || dbTypeName == "string"|| dbTypeName == "jsonb"|| dbTypeName == "json") + else if (dbTypeName == "xml" || dbTypeName == "string") { return "string"; - }else if (dbTypeName == "bpchar")//数据库char datatype 查询出来的时候是 bpchar - { - return "char"; } if (dbTypeName == "byte[]") { @@ -54,63 +78,48 @@ namespace SqlSugar } } } - public static List> MappingTypesConst = new List>(){ + public static List> MappingTypesConst = new List>() + { + new KeyValuePair("int",CSharpDataType.@int), + new KeyValuePair("integer",CSharpDataType.@int), + new KeyValuePair("interval year to month",CSharpDataType.@int), + new KeyValuePair("interval day to second",CSharpDataType.@int), - new KeyValuePair("int2",CSharpDataType.@short), - new KeyValuePair("smallint",CSharpDataType.@short), - new KeyValuePair("int4",CSharpDataType.@int), - new KeyValuePair("integer",CSharpDataType.@int), - new KeyValuePair("int8",CSharpDataType.@long), - new KeyValuePair("bigint",CSharpDataType.@long), - new KeyValuePair("float4",CSharpDataType.@float), - new KeyValuePair("real",CSharpDataType.@float), - new KeyValuePair("float8",CSharpDataType.@double), - new KeyValuePair("double precision",CSharpDataType.@int), - new KeyValuePair("numeric",CSharpDataType.@decimal), - new KeyValuePair("decimal",CSharpDataType.@decimal), - new KeyValuePair("path",CSharpDataType.@decimal), - new KeyValuePair("point",CSharpDataType.@decimal), - new KeyValuePair("polygon",CSharpDataType.@decimal), + new KeyValuePair("number",CSharpDataType.@int), + new KeyValuePair("number",CSharpDataType.@float), + new KeyValuePair("number",CSharpDataType.@short), + new KeyValuePair("number",CSharpDataType.@byte), + new KeyValuePair("number",CSharpDataType.@double), + new KeyValuePair("number",CSharpDataType.@long), + new KeyValuePair("number",CSharpDataType.@bool), + new KeyValuePair("number",CSharpDataType.@decimal), + new KeyValuePair("number",CSharpDataType.Single), + new KeyValuePair("decimal",CSharpDataType.@decimal), + new KeyValuePair("decimal",CSharpDataType.Single), - new KeyValuePair("boolean",CSharpDataType.@bool), - new KeyValuePair("bool",CSharpDataType.@bool), - new KeyValuePair("box",CSharpDataType.@bool), - new KeyValuePair("bytea",CSharpDataType.@bool), + new KeyValuePair("varchar",CSharpDataType.@string), + new KeyValuePair("varchar2",CSharpDataType.@string), + new KeyValuePair("nvarchar2",CSharpDataType.@string), + new KeyValuePair("char",CSharpDataType.@string), + new KeyValuePair("nchar",CSharpDataType.@string), + new KeyValuePair("clob",CSharpDataType.@string), + new KeyValuePair("long",CSharpDataType.@string), + new KeyValuePair("nclob",CSharpDataType.@string), + new KeyValuePair("rowid",CSharpDataType.@string), - new KeyValuePair("varchar",CSharpDataType.@string), - new KeyValuePair("character varying",CSharpDataType.@string), - new KeyValuePair("name",CSharpDataType.@string), - new KeyValuePair("text",CSharpDataType.@string), - new KeyValuePair("char",CSharpDataType.@string), - new KeyValuePair("character",CSharpDataType.@string), - new KeyValuePair("cidr",CSharpDataType.@string), - new KeyValuePair("circle",CSharpDataType.@string), - new KeyValuePair("tsquery",CSharpDataType.@string), - new KeyValuePair("tsvector",CSharpDataType.@string), - new KeyValuePair("txid_snapshot",CSharpDataType.@string), - new KeyValuePair("uuid",CSharpDataType.Guid), - new KeyValuePair("xml",CSharpDataType.@string), - new KeyValuePair("json",CSharpDataType.@string), + new KeyValuePair("date",CSharpDataType.DateTime), + new KeyValuePair("timestamp",CSharpDataType.DateTime), + new KeyValuePair("timestamp with local time zone",CSharpDataType.DateTime), + new KeyValuePair("timestamp with time zone",CSharpDataType.DateTime), + new KeyValuePair("timestamp with time zone",CSharpDataType.DateTime), - new KeyValuePair("interval",CSharpDataType.@decimal), - new KeyValuePair("lseg",CSharpDataType.@decimal), - new KeyValuePair("macaddr",CSharpDataType.@decimal), - new KeyValuePair("money",CSharpDataType.@decimal), - new KeyValuePair("timestamp",CSharpDataType.DateTime), - new KeyValuePair("timestamp with time zone",CSharpDataType.DateTime), - new KeyValuePair("timestamptz",CSharpDataType.DateTime), - new KeyValuePair("timestamp without time zone",CSharpDataType.DateTime), - new KeyValuePair("date",CSharpDataType.DateTime), - new KeyValuePair("time",CSharpDataType.DateTime), - new KeyValuePair("time with time zone",CSharpDataType.DateTime), - new KeyValuePair("timetz",CSharpDataType.DateTime), - new KeyValuePair("time without time zone",CSharpDataType.DateTime), + new KeyValuePair("float",CSharpDataType.@decimal), - new KeyValuePair("bit",CSharpDataType.byteArray), - new KeyValuePair("bit varying",CSharpDataType.byteArray), - new KeyValuePair("varbit",CSharpDataType.@byte), - - }; + new KeyValuePair("blob",CSharpDataType.byteArray), + new KeyValuePair("long raw",CSharpDataType.byteArray), + new KeyValuePair("raw",CSharpDataType.byteArray), + new KeyValuePair("bfile",CSharpDataType.byteArray), + new KeyValuePair("varbinary",CSharpDataType.byteArray) }; public override List StringThrow { get diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/DbMaintenance/DmDbMaintenance.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/DbMaintenance/DmDbMaintenance.cs index 67e242069..f87be33f9 100644 --- a/Src/Asp.Net/SqlSugar/Realization/Dm/DbMaintenance/DmDbMaintenance.cs +++ b/Src/Asp.Net/SqlSugar/Realization/Dm/DbMaintenance/DmDbMaintenance.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Data; +using System.Data.Common; using System.Linq; using System.Text; @@ -12,63 +14,64 @@ namespace SqlSugar { get { - return "SELECT datname FROM pg_database"; + throw new NotSupportedException(); } } protected override string GetColumnInfosByTableNameSql { get { - string sql = @"select cast (pclass.oid as int4) as TableId,cast(ptables.tablename as varchar) as TableName, - pcolumn.column_name as DbColumnName,pcolumn.udt_name as DataType, - pcolumn.character_maximum_length as Length, - pcolumn.column_default as DefaultValue, - col_description(pclass.oid, pcolumn.ordinal_position) as ColumnDescription, - case when pkey.colname = pcolumn.column_name - then true else false end as IsPrimaryKey, - case when pcolumn.column_default like 'nextval%' - then true else false end as IsIdentity, - case when pcolumn.is_nullable = 'YES' - then true else false end as IsNullable - from (select * from pg_tables where tablename = '{0}' and schemaname='public') ptables inner join pg_class pclass - on ptables.tablename = pclass.relname inner join (SELECT * - FROM information_schema.columns - ) pcolumn on pcolumn.table_name = ptables.tablename - left join ( - select pg_class.relname,pg_attribute.attname as colname from - pg_constraint inner join pg_class - on pg_constraint.conrelid = pg_class.oid - inner join pg_attribute on pg_attribute.attrelid = pg_class.oid - and pg_attribute.attnum = pg_constraint.conkey[1] - inner join pg_type on pg_type.oid = pg_attribute.atttypid - where pg_constraint.contype='p' - ) pkey on pcolumn.table_name = pkey.relname - order by ptables.tablename"; - return sql; + throw new NotSupportedException(); } } protected override string GetTableInfoListSql { get { - return @"select cast(relname as varchar) as Name, - cast(obj_description(relfilenode,'pg_class') as varchar) as Description from pg_class c - where relkind = 'r' and relname not like 'pg_%' and relname not like 'sql_%' order by relname"; + return @"SELECT table_name name from user_tables where + table_name!='HELP' + AND table_name NOT LIKE '%$%' + AND table_name NOT LIKE 'LOGMNRC_%' + AND table_name!='LOGMNRP_CTAS_PART_MAP' + AND table_name!='LOGMNR_LOGMNR_BUILDLOG' + AND table_name!='SQLPLUS_PRODUCT_PROFILE' + "; } } protected override string GetViewInfoListSql { get { - return @"select cast(relname as varchar) as Name,cast(Description as varchar) from pg_description - join pg_class on pg_description.objoid = pg_class.oid - where objsubid = 0 and relname in (SELECT viewname from pg_views - WHERE schemaname ='public')"; + return @"select view_name name from user_views + WHERE VIEW_name NOT LIKE '%$%' + AND VIEW_NAME !='PRODUCT_PRIVS' + AND VIEW_NAME NOT LIKE 'MVIEW_%' "; } } #endregion #region DDL + protected override string IsAnyIndexSql + { + get + { + return "select count(1) from user_ind_columns where index_name=('{0}')"; + } + } + protected override string CreateIndexSql + { + get + { + return "CREATE INDEX Index_{0}_{2} ON {0}({1})"; + } + } + protected override string AddDefaultValueSql + { + get + { + return "ALTER TABLE {0} MODIFY({1} DEFAULT '{2}')"; + } + } protected override string CreateDataBaseSql { get @@ -87,28 +90,28 @@ namespace SqlSugar { get { - return "ALTER TABLE {0} ADD COLUMN {1} {2}{3} {4} {5} {6}"; + 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} modify ({1} {2}{3} {4} {5} {6}) "; } } protected override string BackupDataBaseSql { get { - return "mysqldump.exe {0} -uroot -p > {1} "; + return @"USE master;BACKUP DATABASE {0} TO disk = '{1}'"; } } protected override string CreateTableSql { get { - return "CREATE TABLE {0}(\r\n{1} $PrimaryKey)"; + return "CREATE TABLE {0}(\r\n{1})"; } } protected override string CreateTableColumn @@ -129,7 +132,7 @@ namespace SqlSugar { get { - return "create table {0} as (select * from {1} limit {2} offset 0)"; + return "create table {1} as select * from {2} where ROWNUM<={0}"; } } protected override string DropTableSql @@ -150,52 +153,71 @@ namespace SqlSugar { get { - return "ALTER TABLE {0} DROP CONSTRAINT {1}"; + return "ALTER TABLE {0} DROP CONSTRAINT {1}"; } } protected override string RenameColumnSql { get { - return "ALTER TABLE {0} RENAME {1} TO {2}"; + return "ALTER TABLE {0} rename column {1} to {2}"; } } - protected override string AddColumnRemarkSql => "comment on column {1}.{0} is '{2}'"; - - protected override string DeleteColumnRemarkSql => "comment on column {1}.{0} is ''"; - - protected override string IsAnyColumnRemarkSql { get { throw new NotSupportedException(); } } - - protected override string AddTableRemarkSql => "comment on table {0} is '{1}'"; - - protected override string DeleteTableRemarkSql => "comment on table {0} is ''"; - - protected override string IsAnyTableRemarkSql { get { throw new NotSupportedException(); } } - - protected override string RenameTableSql => "alter table 表名 {0} to {1}"; - - protected override string CreateIndexSql + protected override string AddColumnRemarkSql { get { - return "CREATE INDEX Index_{0}_{2} ON {0} ({1})"; - } - } - protected override string AddDefaultValueSql - { - get - { - return "ALTER TABLE {0} ALTER COLUMN {1} SET DEFAULT {2}"; - } - } - protected override string IsAnyIndexSql - { - get - { - return " Select count(1) from (SELECT to_regclass('Index_UnitCodeTest1_Id_CreateDate') as c ) t where t.c is not null"; + return "comment on column {1}.{0} is '{2}'"; } } + protected override string DeleteColumnRemarkSql + { + get + { + return "comment on column {1}.{0} is ''"; + } + } + + protected override string IsAnyColumnRemarkSql + { + get + { + return "select * from user_col_comments where Table_Name='{1}' AND COLUMN_NAME='{0}' order by column_name"; + } + } + + protected override string AddTableRemarkSql + { + get + { + return "comment on table {0} is '{1}'"; + } + } + + protected override string DeleteTableRemarkSql + { + get + { + return "comment on table {0} is ''"; + } + } + + protected override string IsAnyTableRemarkSql + { + get + { + return "select * from user_tab_comments where Table_Name='{0}'order by Table_Name"; + } + } + + protected override string RenameTableSql + { + get + { + return "alter table {0} rename to {1}"; + } + } #endregion #region Check @@ -203,7 +225,7 @@ namespace SqlSugar { get { - return "select 1 from information_schema.columns limit 1 offset 0"; + return "select t.table_name from user_tables t where rownum=1"; } } #endregion @@ -213,14 +235,14 @@ namespace SqlSugar { get { - return "DEFAULT NULL"; + return ""; } } protected override string CreateTableNotNull { get { - return "NOT NULL"; + return ""; } } protected override string CreateTablePirmaryKey @@ -234,40 +256,52 @@ namespace SqlSugar { get { - return "serial"; + return "IDENTITY(1,1)"; } } - #endregion + #endregion #region Methods - /// - ///by current connection string - /// - /// - /// + public override bool AddColumn(string tableName, DbColumnInfo columnInfo) + { + if (columnInfo.DataType == "varchar" && columnInfo.Length == 0) + { + columnInfo.DataType = "varchar2"; + columnInfo.Length = 50; + } + return base.AddColumn(tableName, columnInfo); + } + public override bool CreateIndex(string tableName, string[] columnNames) + { + string sql = string.Format(CreateIndexSql, tableName, string.Join(",", columnNames), string.Join("_", columnNames.Select(it => (it + "abc").Substring(0, 3)))); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + public override bool AddDefaultValue(string tableName, string columnName, string defaultValue) + { + if (defaultValue == "''") + { + defaultValue = ""; + } + if (defaultValue.ToLower().IsIn("sysdate")) + { + var template = AddDefaultValueSql.Replace("'", ""); + string sql = string.Format(template, tableName, columnName, defaultValue); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + else + { + return base.AddDefaultValue(tableName, columnName, defaultValue); + } + } + public override bool CreateDatabase(string databaseDirectory = null) + { + throw new NotSupportedException(); + } public override bool CreateDatabase(string databaseName, string databaseDirectory = null) { - if (databaseDirectory != null) - { - if (!FileHelper.IsExistDirectory(databaseDirectory)) - { - FileHelper.CreateDirectory(databaseDirectory); - } - } - var oldDatabaseName = this.Context.Ado.Connection.Database; - var connection = this.Context.CurrentConnectionConfig.ConnectionString; - connection = connection.Replace(oldDatabaseName, "postgres"); - 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, this.SqlBuilder.SqlTranslationLeft+databaseName+this.SqlBuilder.SqlTranslationRight, databaseDirectory)); - } - return true; + throw new NotSupportedException(); } public override bool AddRemark(EntityInfo entity) { @@ -278,17 +312,131 @@ namespace SqlSugar { if (item.ColumnDescription != null) { - db.DbMaintenance.AddColumnRemark(item.DbColumnName, item.DbTableName, item.ColumnDescription); - + //column remak + if (db.DbMaintenance.IsAnyColumnRemark(item.DbColumnName.ToUpper(), item.DbTableName.ToUpper())) + { + db.DbMaintenance.DeleteColumnRemark(item.DbColumnName.ToUpper(), item.DbTableName.ToUpper()); + db.DbMaintenance.AddColumnRemark(item.DbColumnName.ToUpper(), item.DbTableName.ToUpper(), item.ColumnDescription); + } + else + { + db.DbMaintenance.AddColumnRemark(item.DbColumnName.ToUpper(), item.DbTableName.ToUpper(), item.ColumnDescription); + } } } + //table remak if (entity.TableDescription != null) { - db.DbMaintenance.AddTableRemark(entity.DbTableName, entity.TableDescription); + if (db.DbMaintenance.IsAnyTableRemark(entity.DbTableName)) + { + db.DbMaintenance.DeleteTableRemark(entity.DbTableName); + db.DbMaintenance.AddTableRemark(entity.DbTableName, entity.TableDescription); + } + else + { + db.DbMaintenance.AddTableRemark(entity.DbTableName, entity.TableDescription); + } } return true; } + public override List GetColumnInfosByTableName(string tableName, bool isCache = true) + { + string cacheKey = "DbMaintenanceProvider.GetColumnInfosByTableName." + this.SqlBuilder.GetNoTranslationColumnName(tableName).ToLower(); + cacheKey = GetCacheKey(cacheKey); + if (!isCache) + return GetColumnInfosByTableName(tableName); + else + return this.Context.Utilities.GetReflectionInoCacheInstance().GetOrCreate(cacheKey, + () => + { + return GetColumnInfosByTableName(tableName); + + }); + } + + private List GetColumnInfosByTableName(string tableName) + { + string sql = "select * from " + SqlBuilder.GetTranslationTableName(tableName) + " WHERE 1=2 "; + var oldIsEnableLog = this.Context.Ado.IsEnableLogEvent; + this.Context.Ado.IsEnableLogEvent = false; + using (DbDataReader reader = (DbDataReader)this.Context.Ado.GetDataReader(sql)) + { + this.Context.Ado.IsEnableLogEvent = oldIsEnableLog; + List result = new List(); + var schemaTable = reader.GetSchemaTable(); + foreach (System.Data.DataRow row in schemaTable.Rows) + { + DbColumnInfo column = new DbColumnInfo() + { + TableName = tableName, + DataType = row["DataType"].ToString().Replace("System.", "").Trim(), + IsNullable = (bool)row["AllowDBNull"], + IsIdentity = (bool)row["IsIdentity"], + ColumnDescription = GetFieldComment(tableName, row["ColumnName"].ToString()), + DbColumnName = row["ColumnName"].ToString(), + //DefaultValue = row["defaultValue"].ToString(), + IsPrimarykey = GetPrimaryKeyByTableNames(tableName).Any(it => it.Equals(row["ColumnName"].ToString(), StringComparison.CurrentCultureIgnoreCase)), + Length = row["ColumnSize"].ObjToInt(), + Scale = row["numericscale"].ObjToInt() + }; + result.Add(column); + } + return result; + } + } + + private List GetPrimaryKeyByTableNames(string tableName) + { + string cacheKey = "DbMaintenanceProvider.GetPrimaryKeyByTableNames." + this.SqlBuilder.GetNoTranslationColumnName(tableName).ToLower(); + cacheKey = GetCacheKey(cacheKey); + return this.Context.Utilities.GetReflectionInoCacheInstance().GetOrCreate(cacheKey, + () => + { + var oldIsEnableLog = this.Context.Ado.IsEnableLogEvent; + this.Context.Ado.IsEnableLogEvent = false; + string sql = @" select distinct cu.COLUMN_name KEYNAME from user_cons_columns cu, user_constraints au + where cu.constraint_name = au.constraint_name + and au.constraint_type = 'P' and au.table_name = '" + tableName.ToUpper() + @"'"; + var pks = this.Context.Ado.SqlQuery(sql); + this.Context.Ado.IsEnableLogEvent = oldIsEnableLog; + return pks; + }); + } + + public string GetTableComment(string tableName) + { + string cacheKey = "DbMaintenanceProvider.GetTableComment." + tableName; + var comments = this.Context.Utilities.GetReflectionInoCacheInstance().GetOrCreate(cacheKey, + () => + { + string sql = "SELECT COMMENTS FROM USER_TAB_COMMENTS WHERE TABLE_NAME =@tableName ORDER BY TABLE_NAME"; + var oldIsEnableLog = this.Context.Ado.IsEnableLogEvent; + this.Context.Ado.IsEnableLogEvent = false; + var pks = this.Context.Ado.SqlQuery(sql, new { tableName = tableName.ToUpper() }); + this.Context.Ado.IsEnableLogEvent = oldIsEnableLog; + return pks; + }); + return comments.HasValue() ? comments.First() : ""; + } + + public string GetFieldComment(string tableName, string filedName) + { + string cacheKey = "DbMaintenanceProvider.GetFieldComment." + tableName; + var comments = this.Context.Utilities.GetReflectionInoCacheInstance().GetOrCreate(cacheKey, + () => + { + string sql = "SELECT TVNAME AS TableName, COLNAME,COMMENT$ AS ColumnDescription from SYSCOLUMNCOMMENTS WHERE TVNAME='"+ tableName.ToUpper() + "' ORDER BY TVNAME"; + var oldIsEnableLog = this.Context.Ado.IsEnableLogEvent; + this.Context.Ado.IsEnableLogEvent = false; + var pks = this.Context.Ado.SqlQuery(sql); + this.Context.Ado.IsEnableLogEvent = oldIsEnableLog; + return pks; + }); + return comments.HasValue() ? comments.First(it => it.DbColumnName.Equals(filedName, StringComparison.CurrentCultureIgnoreCase)).ColumnDescription : ""; + + } + public override bool CreateTable(string tableName, List columns, bool isCreatePrimaryKey = true) { if (columns.HasValue()) @@ -312,52 +460,6 @@ namespace SqlSugar this.Context.Ado.ExecuteCommand(sql); return true; } - protected override string GetCreateTableSql(string tableName, List columns) - { - List columnArray = new List(); - Check.Exception(columns.IsNullOrEmpty(), "No columns found "); - foreach (var item in columns) - { - string columnName = item.DbColumnName; - string dataType = item.DataType; - if (dataType == "varchar" && item.Length == 0) - { - item.Length = 1; - } - if (dataType == "uuid") - { - item.Length = 50; - dataType = "varchar"; - } - string dataSize = item.Length > 0 ? string.Format("({0})", item.Length) : null; - string nullType = item.IsNullable ? this.CreateTableNull : CreateTableNotNull; - string primaryKey = null; - string addItem = string.Format(this.CreateTableColumn, this.SqlBuilder.GetTranslationColumnName(columnName.ToLower()), dataType, dataSize, nullType, primaryKey, ""); - if (item.IsIdentity) - { - string length = dataType.Substring(dataType.Length - 1); - string identityDataType = "serial" + length; - addItem = addItem.Replace(dataType, identityDataType); - } - columnArray.Add(addItem); - } - string tableString = string.Format(this.CreateTableSql, this.SqlBuilder.GetTranslationTableName(tableName.ToLower()), string.Join(",\r\n", columnArray)); - return tableString; - } - public override bool IsAnyConstraint(string constraintName) - { - throw new NotSupportedException("PgSql IsAnyConstraint NotSupportedException"); - } - public override bool BackupDataBase(string databaseName, string fullFileName) - { - Check.ThrowNotSupportedException("PgSql BackupDataBase NotSupported"); - return false; - } - - public override List GetColumnInfosByTableName(string tableName, bool isCache = true) - { - return base.GetColumnInfosByTableName(tableName.TrimEnd('"').TrimStart('"').ToLower(), isCache); - } #endregion } } diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/DmProvider.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/DmProvider.cs index 1c50e0ffa..1f22ca755 100644 --- a/Src/Asp.Net/SqlSugar/Realization/Dm/DmProvider.cs +++ b/Src/Asp.Net/SqlSugar/Realization/Dm/DmProvider.cs @@ -4,6 +4,7 @@ using System.Data; using System.Data.Common; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; using Dm; @@ -12,7 +13,29 @@ namespace SqlSugar { public partial class DmProvider : AdoProvider { - public DmProvider() { } + public DmProvider() { + this.FormatSql = sql => + { + var guid = Guid.NewGuid(); + sql = sql.Replace("+@", "+:"); + sql = sql.Replace("select @@identity", guid.ToString()); + if (sql.HasValue() && sql.Contains("@")) + { + var exceptionalCaseInfo = Regex.Matches(sql, @"\'.*?\@.*?\'| [\.,\w]+\@[\.,\w]+ | [\.,\w]+\@[\.,\w]+"); + if (exceptionalCaseInfo != null) + { + foreach (var item in exceptionalCaseInfo.Cast()) + { + sql = sql.Replace(item.Value, item.Value.Replace("@", UtilConstants.ReplaceKey)); + } + } + sql = sql.Replace("@", ":"); + sql = sql.Replace(UtilConstants.ReplaceKey, "@"); + } + sql = sql.Replace(guid.ToString(), "select @@identity"); + return sql; + }; + } public override IDbConnection Connection { get @@ -94,11 +117,11 @@ namespace SqlSugar sqlParameter.Size = parameter.Size; sqlParameter.Value = parameter.Value; sqlParameter.DbType = parameter.DbType; - sqlParameter.Direction = parameter.Direction; - if (sqlParameter.Direction == 0) + if (parameter.Direction == 0) { - sqlParameter.Direction = ParameterDirection.Input; + parameter.Direction = ParameterDirection.Input; } + sqlParameter.Direction = parameter.Direction; result[index] = sqlParameter; if (sqlParameter.Direction.IsIn(ParameterDirection.Output, ParameterDirection.InputOutput, ParameterDirection.ReturnValue)) { diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/Insertable/DmInserttable.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/Insertable/DmInserttable.cs index 7f80de97c..8da13a061 100644 --- a/Src/Asp.Net/SqlSugar/Realization/Dm/Insertable/DmInserttable.cs +++ b/Src/Asp.Net/SqlSugar/Realization/Dm/Insertable/DmInserttable.cs @@ -9,66 +9,6 @@ namespace SqlSugar { public class DmInserttable : InsertableProvider where T : class, new() { - public override int ExecuteReturnIdentity() - { - InsertBuilder.IsReturnIdentity = true; - PreToSql(); - string sql = InsertBuilder.ToSqlString().Replace("$PrimaryKey", GetIdentityKeys().FirstOrDefault()); - RestoreMapping(); - var result = Ado.GetScalar(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray()).ObjToInt(); - return result; - } - public override async Task ExecuteReturnIdentityAsync() - { - InsertBuilder.IsReturnIdentity = true; - PreToSql(); - string sql = InsertBuilder.ToSqlString().Replace("$PrimaryKey", GetIdentityKeys().FirstOrDefault()); - RestoreMapping(); - var obj = await Ado.GetScalarAsync(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray()); - var result = obj.ObjToInt(); - return result; - } - public override KeyValuePair> ToSql() - { - var result= base.ToSql(); - return new KeyValuePair>(result.Key.Replace("$PrimaryKey", GetPrimaryKeys().FirstOrDefault()), result.Value); - } - - public override long ExecuteReturnBigIdentity() - { - InsertBuilder.IsReturnIdentity = true; - PreToSql(); - string sql = InsertBuilder.ToSqlString().Replace("$PrimaryKey", GetIdentityKeys().FirstOrDefault()); - RestoreMapping(); - var result = Convert.ToInt64(Ado.GetScalar(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray()) ?? "0"); - return result; - } - public override async Task ExecuteReturnBigIdentityAsync() - { - InsertBuilder.IsReturnIdentity = true; - PreToSql(); - string sql = InsertBuilder.ToSqlString().Replace("$PrimaryKey", GetIdentityKeys().FirstOrDefault()); - RestoreMapping(); - var result = Convert.ToInt64(await Ado.GetScalarAsync(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray()) ?? "0"); - return result; - } - - public override bool ExecuteCommandIdentityIntoEntity() - { - var result = InsertObjs.First(); - var identityKeys = GetIdentityKeys(); - if (identityKeys.Count == 0) { return this.ExecuteCommand() > 0; } - var idValue = ExecuteReturnBigIdentity(); - Check.Exception(identityKeys.Count > 1, "ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); - var identityKey = identityKeys.First(); - object setValue = 0; - if (idValue > int.MaxValue) - setValue = idValue; - else - setValue = Convert.ToInt32(idValue); - var propertyName = this.Context.EntityMaintenance.GetPropertyName(identityKey); - typeof(T).GetProperties().First(t => t.Name.ToUpper() == propertyName.ToUpper()).SetValue(result, setValue, null); - return idValue > 0; - } + } } diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmBuilder.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmBuilder.cs new file mode 100644 index 000000000..4f7e65f9e --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmBuilder.cs @@ -0,0 +1,51 @@ +using System; +using System.Linq; +using System.Text.RegularExpressions; + +namespace SqlSugar +{ + public class DmBuilder : SqlBuilderProvider + { + public override string SqlParameterKeyWord + { + get + { + return ":"; + } + } + public override string SqlDateNow + { + get + { + return "sysdate"; + } + } + public override string FullSqlDateNow + { + get + { + return "select sysdate from dual"; + } + } + public override string SqlTranslationLeft { get { return "\""; } } + public override string SqlTranslationRight { get { return "\""; } } + public override string GetTranslationTableName(string name) + { + var result = base.GetTranslationTableName(name); + if (result.Contains("(") && result.Contains(")")) + return result; + else + return result.ToUpper(); + } + public override string GetTranslationColumnName(string entityName, string propertyName) + { + var result = base.GetTranslationColumnName(entityName, propertyName); + return result.ToUpper(); + } + public override string GetTranslationColumnName(string propertyName) + { + var result = base.GetTranslationColumnName(propertyName); + return result.ToUpper(); + } + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmExpressionContext.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmExpressionContext.cs index cede5ba29..ffdb65f34 100644 --- a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmExpressionContext.cs +++ b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmExpressionContext.cs @@ -1,262 +1,200 @@ 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 { - public class DmExpressionContext : ExpressionContext, ILambdaExpressions + public partial class DmExpressionContext : ExpressionContext, ILambdaExpressions { public SqlSugarProvider Context { get; set; } public DmExpressionContext() { base.DbMehtods = new DmMethod(); } - public override string SqlTranslationLeft + public override string SqlParameterKeyWord { get { - return "\""; - } - } - public override string SqlTranslationRight - { - get - { - return "\""; - } - } - public override string GetTranslationText(string name) - { - return SqlTranslationLeft + name.ToLower(isAutoToLower) + SqlTranslationRight; - } - public bool isAutoToLower - { - get - { - return base.PgSqlIsAutoToLower; + return ":"; } } + public override string SqlTranslationLeft { get { return "\""; } } + public override string SqlTranslationRight { get { return "\""; } } public override string GetTranslationTableName(string entityName, bool isMapping = true) { - Check.ArgumentNullException(entityName, string.Format(ErrorMessage.ObjNotExist, "Table Name")); - if (IsTranslationText(entityName)) return entityName; - isMapping = isMapping && this.MappingTables.HasValue(); - var isComplex = entityName.Contains(UtilConstants.Dot); - if (isMapping && isComplex) - { - var columnInfo = entityName.Split(UtilConstants.DotChar); - var mappingInfo = this.MappingTables.FirstOrDefault(it => it.EntityName.Equals(columnInfo.Last(), StringComparison.CurrentCultureIgnoreCase)); - if (mappingInfo != null) - { - columnInfo[columnInfo.Length - 1] = mappingInfo.EntityName; - } - return string.Join(UtilConstants.Dot, columnInfo.Select(it => GetTranslationText(it))); - } - else if (isMapping) - { - var mappingInfo = this.MappingTables.FirstOrDefault(it => it.EntityName.Equals(entityName, StringComparison.CurrentCultureIgnoreCase)); - return SqlTranslationLeft + (mappingInfo == null ? entityName : mappingInfo.DbTableName).ToLower(isAutoToLower) + SqlTranslationRight; - } - else if (isComplex) - { - return string.Join(UtilConstants.Dot, entityName.Split(UtilConstants.DotChar).Select(it => GetTranslationText(it))); - } - else - { - return GetTranslationText(entityName); - } + return base.GetTranslationTableName(entityName, isMapping).ToUpper(); } public override string GetTranslationColumnName(string columnName) { - Check.ArgumentNullException(columnName, string.Format(ErrorMessage.ObjNotExist, "Column Name")); - if (columnName.Substring(0, 1) == this.SqlParameterKeyWord) - { - return columnName; - } - if (IsTranslationText(columnName)) return columnName; - if (columnName.Contains(UtilConstants.Dot)) - { - return string.Join(UtilConstants.Dot, columnName.Split(UtilConstants.DotChar).Select(it => GetTranslationText(it))); - } - else - { - return GetTranslationText(columnName); - } + return base.GetTranslationColumnName(columnName).ToUpper(); } public override string GetDbColumnName(string entityName, string propertyName) { - if (this.MappingColumns.HasValue()) - { - var mappingInfo = this.MappingColumns.SingleOrDefault(it => it.EntityName == entityName && it.PropertyName == propertyName); - return (mappingInfo == null ? propertyName : mappingInfo.DbColumnName).ToLower(isAutoToLower); - } - else - { - return propertyName.ToLower(isAutoToLower); - } + return base.GetDbColumnName(entityName, propertyName).ToUpper(); } } - public class DmMethod : DefaultDbMethod, IDbMethods + public partial class DmMethod : DefaultDbMethod, IDbMethods { - public override string DateValue(MethodCallExpressionModel model) + public override string ToInt64(MethodCallExpressionModel model) { var parameter = model.Args[0]; - var parameter2 = model.Args[1]; - var format = "dd"; - if (parameter2.MemberValue.ObjToString() == DateType.Year.ToString()) - { - format = "yyyy"; - } - if (parameter2.MemberValue.ObjToString() == DateType.Month.ToString()) - { - format = "MM"; - } - if (parameter2.MemberValue.ObjToString() == DateType.Day.ToString()) - { - format = "dd"; - } - if (parameter2.MemberValue.ObjToString() == DateType.Hour.ToString()) - { - format = "hh"; - } - if (parameter2.MemberValue.ObjToString() == DateType.Minute.ToString()) - { - format = "mm"; - } - if (parameter2.MemberValue.ObjToString() == DateType.Second.ToString()) - { - format = "ss"; - } - if (parameter2.MemberValue.ObjToString() == DateType.Millisecond.ToString()) - { - format = "ss"; - } - return string.Format(" cast( to_char({1},'{0}')as integer ) ", format, parameter.MemberName); + return string.Format(" CAST({0} AS Number)", parameter.MemberName); } - public override string Contains(MethodCallExpressionModel model) + public override string ToTime(MethodCallExpressionModel model) { var parameter = model.Args[0]; - var parameter2 = model.Args[1]; - return string.Format(" ({0} like concat('%',{1},'%')) ", parameter.MemberName, parameter2.MemberName ); + return string.Format(" to_timestamp({0},'0000-01-01 hh24:mi:ss') ", parameter.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(" (date_part('day',{0}-{1})=0) ", parameter.MemberName, parameter2.MemberName); ; - } - - public override string DateIsSameByType(MethodCallExpressionModel model) + public override string Substring(MethodCallExpressionModel model) { var parameter = model.Args[0]; var parameter2 = model.Args[1]; var parameter3 = model.Args[2]; - return string.Format(" (date_part('{2}',{0}-{1})=0) ", parameter.MemberName, parameter2.MemberName, parameter3.MemberValue); + return string.Format("SUBSTR({0},1 + {1},{2})", parameter.MemberName, parameter2.MemberName, parameter3.MemberName); } - - public override string ToDate(MethodCallExpressionModel model) + public override string DateValue(MethodCallExpressionModel model) { var parameter = model.Args[0]; - return string.Format(" CAST({0} AS timestamp)", parameter.MemberName); + var parameter2 = model.Args[1]; + var type = (DateType)Enum.Parse(typeof(DateType), parameter2.MemberValue.ObjToString(), false); + switch (type) + { + case DateType.Year: + return string.Format("(CAST(TO_CHAR({0},'yyyy') AS NUMBER))", parameter.MemberName); + case DateType.Month: + return string.Format("(CAST(TO_CHAR({0},'mm') AS NUMBER))", parameter.MemberName); + case DateType.Hour: + return string.Format("(CAST(TO_CHAR({0},'hh24') AS NUMBER))", parameter.MemberName); + case DateType.Second: + return string.Format("(CAST(TO_CHAR({0},'ss') AS NUMBER))", parameter.MemberName); + case DateType.Minute: + return string.Format("(CAST(TO_CHAR({0},'mi') AS NUMBER))", parameter.MemberName); + case DateType.Millisecond: + return string.Format("(CAST(TO_CHAR({0},'ff3') AS NUMBER))", parameter.MemberName); + case DateType.Day: + default: + return string.Format("(CAST(TO_CHAR({0},'dd') AS NUMBER))", parameter.MemberName); + } } public override string DateAddByType(MethodCallExpressionModel model) { var parameter = model.Args[0]; var parameter2 = model.Args[1]; var parameter3 = model.Args[2]; - return string.Format(" ({1} + ({2}||'{0}')::INTERVAL) ", parameter3.MemberValue, parameter.MemberName, parameter2.MemberName); + var type = (DateType)Enum.Parse(typeof(DateType), parameter3.MemberValue.ObjToString(), false); + double time = 1; + switch (type) + { + case DateType.Year: + time = 1 * 365; + break; + case DateType.Month: + time = 1 * 30; + break; + case DateType.Day: + break; + case DateType.Hour: + time = 1 / 24.0; + break; + case DateType.Second: + time = 1 / 24.0 / 60.0 / 60.0; + break; + case DateType.Minute: + time = 1 / 24.0 / 60.0; + break; + case DateType.Millisecond: + time = 1 / 24.0 / 60.0 / 60.0 / 1000; + break; + } + return string.Format("({0}+({1}*{2})) ", parameter.MemberName, time, parameter2.MemberName); } public override string DateAddDay(MethodCallExpressionModel model) { var parameter = model.Args[0]; var parameter2 = model.Args[1]; - return string.Format(" ({0} + ({1}||'day')::INTERVAL) ", parameter.MemberName, parameter2.MemberName); - } - - public override string ToInt32(MethodCallExpressionModel model) - { - var parameter = model.Args[0]; - return string.Format(" CAST({0} AS SIGNED)", parameter.MemberName); - } - - public override string ToInt64(MethodCallExpressionModel model) - { - var parameter = model.Args[0]; - return string.Format(" CAST({0} AS SIGNED)", parameter.MemberName); + return string.Format("({0}+(1*{1})) ", parameter.MemberName, parameter2.MemberName); } public override string ToString(MethodCallExpressionModel model) { var parameter = model.Args[0]; - return string.Format(" CAST({0} AS VARCHAR)", parameter.MemberName); + return string.Format(" CAST({0} AS VARCHAR2(4000))", parameter.MemberName); } - public override string ToGuid(MethodCallExpressionModel model) + public override string ToDate(MethodCallExpressionModel model) { var parameter = model.Args[0]; - return string.Format(" CAST({0} AS VARCHAR)", parameter.MemberName); + return string.Format(" to_date({0},'yyyy-mm-dd hh24:mi:ss')", parameter.MemberName); } - - public override string ToDouble(MethodCallExpressionModel model) + public override string Contains(MethodCallExpressionModel model) { var parameter = model.Args[0]; - return string.Format(" CAST({0} AS DECIMAL(18,4))", parameter.MemberName); + var parameter2 = model.Args[1]; + return string.Format(" ({0} like '%'||{1}||'%') ", parameter.MemberName, parameter2.MemberName); } - - public override string ToBool(MethodCallExpressionModel model) + public override string StartsWith(MethodCallExpressionModel model) { var parameter = model.Args[0]; - return string.Format(" CAST({0} AS SIGNED)", parameter.MemberName); + var parameter2 = model.Args[1]; + return string.Format(" ({0} like {1}||'%') ", parameter.MemberName, parameter2.MemberName); } - - public override string ToDecimal(MethodCallExpressionModel model) + public override string EndsWith(MethodCallExpressionModel model) { var parameter = model.Args[0]; - return string.Format(" CAST({0} AS DECIMAL(18,4))", parameter.MemberName); + var parameter2 = model.Args[1]; + return string.Format(" ({0} like '%'||{1}) ", parameter.MemberName, parameter2.MemberName); + } + public override string Trim(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" trim({0}) ", parameter.MemberName); + } + public override string DateIsSameDay(MethodCallExpressionModel model) + { + throw new NotSupportedException("Oracle NotSupportedException DateIsSameDay"); + } + public override string DateIsSameByType(MethodCallExpressionModel model) + { + throw new NotSupportedException("Oracle NotSupportedException DateIsSameDay"); } - public override string Length(MethodCallExpressionModel model) { var parameter = model.Args[0]; - return string.Format(" LENGTH({0})", parameter.MemberName); - } - public override string MergeString(params string[] strings) - { - return " concat("+string.Join(",", strings).Replace("+", "") + ") "; + return string.Format(" LENGTH({0}) ", parameter.MemberName); } + public override string IsNull(MethodCallExpressionModel model) { var parameter = model.Args[0]; var parameter1 = model.Args[1]; - return string.Format("(CASE WHEN {0} IS NULL THEN {1} ELSE {0} END)", parameter.MemberName, parameter1.MemberName); - } - public override string GetDate() - { - return "NOW()"; - } - public override string GetRandom() - { - return "RANDOM()"; + return string.Format("NVL({0},{1})", parameter.MemberName, parameter1.MemberName); } - public override string EqualTrue(string fieldName) + public override string MergeString(params string[] strings) { - return "( " + fieldName + "=true )"; + return string.Join("||", strings); + } + + public override string GetDate() + { + return "sysdate"; + } + + public override string GetRandom() + { + return "dbms_random.value"; + } + + public override string CharIndex(MethodCallExpressionModel model) + { + return string.Format("instr ({0},{1},1,1) ", model.Args[0].MemberName, model.Args[1].MemberName); } } } diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmInsertBuilder.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmInsertBuilder.cs index b1324a52e..29a9415ae 100644 --- a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmInsertBuilder.cs +++ b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmInsertBuilder.cs @@ -15,7 +15,7 @@ namespace SqlSugar return @"INSERT INTO {0} ({1}) VALUES - ({2}) returning $PrimaryKey"; + ({2}) ;select @@identity"; } else { @@ -27,67 +27,77 @@ namespace SqlSugar } } } + public override string SqlTemplateBatchUnion + { + get + { + return "\t\r\nUNION ALL "; + } + } public override string SqlTemplateBatch => "INSERT INTO {0} ({1})"; - public override string SqlTemplateBatchUnion => " VALUES "; - + public override string SqlTemplateBatchSelect => " {0} "; 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; - 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 ( " + string.Join(",", columns.Select(it => - { - object value = null; - if (it.Value is DateTime) - { - value = ((DateTime)it.Value).ToString("O"); - } - else - { - value = it.Value; - } - if (value == null||value==DBNull.Value) - { - return string.Format(SqlTemplateBatchSelect, "NULL"); - } - return string.Format(SqlTemplateBatchSelect, "'" + value.ObjToString().ToSqlFilter() + "'"); - })) + "),"); - ++i; - } - pageIndex++; - batchInsetrSql.Remove(batchInsetrSql.Length - 1,1).Append("\r\n;\r\n"); - } - return batchInsetrSql.ToString(); - } + return base.ToSqlString(); } + //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; + // 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 ( " + string.Join(",", columns.Select(it => + // { + // object value = null; + // if (it.Value is DateTime) + // { + // value = ((DateTime)it.Value).ToString("O"); + // } + // else + // { + // value = it.Value; + // } + // if (value == null||value==DBNull.Value) + // { + // return string.Format(SqlTemplateBatchSelect, "NULL"); + // } + // return string.Format(SqlTemplateBatchSelect, "'" + value.ObjToString().ToSqlFilter() + "'"); + // })) + "),"); + // ++i; + // } + // pageIndex++; + // batchInsetrSql.Remove(batchInsetrSql.Length - 1,1).Append("\r\n;\r\n"); + // } + // return batchInsetrSql.ToString(); + // } + //} } } diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmQueryBuilder.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmQueryBuilder.cs index d61965171..955459c97 100644 --- a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmQueryBuilder.cs +++ b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmQueryBuilder.cs @@ -6,88 +6,75 @@ namespace SqlSugar { public partial class DmQueryBuilder : QueryBuilder { - #region Sql Template - public override string PageTempalte - { - get - { - /* - SELECT * FROM TABLE WHERE CONDITION ORDER BY ID DESC LIMIT 10 offset 0 - */ - var template = "SELECT {0} FROM {1} {2} {3} {4} LIMIT {6} offset {5}"; - return template; - } - } - public override string DefaultOrderByTemplate - { - get - { - return "ORDER BY NOW() "; - } - } - - #endregion - - #region Common Methods public override bool IsComplexModel(string sql) { return Regex.IsMatch(sql, @"AS ""\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; - return result; - } - - #endregion - - #region Get SQL Partial - public override string GetSelectValue + public override string SqlTemplate { get { - string result = string.Empty; - if (this.SelectValue == null || this.SelectValue is string) + 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 " + this.Builder.SqlDateNow + " "; + if (this.PartitionByValue.HasValue()) + { + this.OrderByValue = this.PartitionByValue + this.OrderByValue; + } + var isRowNumber = 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, GetSelectValue, GetTableNameString, GetWhereValueString, groupByValue, orderByValue); + sql.Replace(UtilConstants.ReplaceKey, isRowNumber ? (isIgnoreOrderBy ? null : rowNumberString) : null); + if (isIgnoreOrderBy) { this.OrderByValue = oldOrderBy; return sql.ToString(); } + var result = ToPageSql(sql.ToString(), this.Take, this.Skip); + if (ExternalPageIndex > 0) + { + if (externalOrderBy.IsNullOrEmpty()) { - result = GetSelectValueByString(); + externalOrderBy = " ORDER BY " + this.Builder.SqlDateNow + " "; } - else - { - result = GetSelectValueByExpression(); - } - if (this.SelectType == ResolveExpressType.SelectMultiple) - { - this.SelectCacheKey = this.SelectCacheKey + string.Join("-", this.JoinQueryInfos.Select(it => it.TableName)); - } - return result; + result = string.Format("SELECT *,ROW_NUMBER() OVER({0}) AS RowIndex2 FROM ({1}) ExternalTable ", GetExternalOrderBy(externalOrderBy), result); + result = ToPageSql2(result, ExternalPageIndex, ExternalPageSize, true); + } + this.OrderByValue = oldOrderBy; + return result; + } + public override string ToPageSql(string sql, int? take, int? skip, bool isExternal = false) + { + string temp = isExternal ? ExternalPageTempalte : PageTempalte; + if (skip != null && take == null) + { + return string.Format(temp, sql.ToString(), skip.ObjToInt() + 1, long.MaxValue); + } + else if (skip == null && take != null) + { + return string.Format(temp, sql.ToString(), 1, take.ObjToInt()); + } + else if (skip != null && take != null) + { + return string.Format(temp, sql.ToString(), skip.ObjToInt() + 1, skip.ObjToInt() + take.ObjToInt()); + } + else + { + return sql.ToString(); } } - #endregion + public override string ToPageSql2(string sql, int? pageIndex, int? pageSize, bool isExternal = false) + { + string temp = isExternal ? ExternalPageTempalte : PageTempalte; + return string.Format(temp, sql.ToString(), (pageIndex - 1) * pageSize + 1, pageIndex * pageSize); + } } } diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmSQLBuilder.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmSQLBuilder.cs deleted file mode 100644 index f308883cf..000000000 --- a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmSQLBuilder.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Linq; -using System.Text.RegularExpressions; - -namespace SqlSugar -{ - public class DmSQLBuilder : SqlBuilderProvider - { - public override string SqlTranslationLeft - { - get - { - return "\""; - } - } - public override string SqlTranslationRight - { - get - { - return "\""; - } - } - public override string SqlDateNow - { - get - { - return "current_date"; - } - } - public override string FullSqlDateNow - { - get - { - return "select current_date"; - } - } - - public bool isAutoToLower - { - get - { - if (this.Context.CurrentConnectionConfig.MoreSettings == null) return true; - return this.Context.CurrentConnectionConfig.MoreSettings.PgSqlIsAutoToLower; - } - } - public override string GetTranslationColumnName(string propertyName) - { - if (propertyName.Contains(SqlTranslationLeft)) return propertyName; - else - return SqlTranslationLeft + propertyName.ToLower(isAutoToLower) + SqlTranslationRight; - } - - //public override string GetNoTranslationColumnName(string name) - //{ - // return name.TrimEnd(Convert.ToChar(SqlTranslationRight)).TrimStart(Convert.ToChar(SqlTranslationLeft)).ToLower(); - //} - public override string GetTranslationColumnName(string entityName, string propertyName) - { - Check.ArgumentNullException(entityName, string.Format(ErrorMessage.ObjNotExist, "Table Name")); - Check.ArgumentNullException(propertyName, string.Format(ErrorMessage.ObjNotExist, "Column Name")); - var context = this.Context; - var mappingInfo = context - .MappingColumns - .FirstOrDefault(it => - it.EntityName.Equals(entityName, StringComparison.CurrentCultureIgnoreCase) && - it.PropertyName.Equals(propertyName, StringComparison.CurrentCultureIgnoreCase)); - return (mappingInfo == null ? SqlTranslationLeft + propertyName.ToLower(isAutoToLower) + SqlTranslationRight : SqlTranslationLeft + mappingInfo.DbColumnName.ToLower(isAutoToLower) + SqlTranslationRight); - } - - public override string GetTranslationTableName(string name) - { - Check.ArgumentNullException(name, string.Format(ErrorMessage.ObjNotExist, "Table Name")); - var context = this.Context; - - var mappingInfo = context - .MappingTables - .FirstOrDefault(it => it.EntityName.Equals(name, StringComparison.CurrentCultureIgnoreCase)); - name = (mappingInfo == null ? name : mappingInfo.DbTableName); - if (name.Contains(".")&& !name.Contains("(")) - { - return string.Join(".", name.ToLower(isAutoToLower).Split('.').Select(it => SqlTranslationLeft + it + SqlTranslationRight)); - } - else if (name.Contains("(")) - { - return name; - } - else if (name.Contains(SqlTranslationLeft) && name.Contains(SqlTranslationRight)) - { - return name; - } - else - { - return SqlTranslationLeft + name.ToLower(isAutoToLower).TrimEnd('"').TrimStart('"') + SqlTranslationRight; - } - } - } -} diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmSQLUpdateBuilder.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmSQLUpdateBuilder.cs deleted file mode 100644 index 629087e38..000000000 --- a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmSQLUpdateBuilder.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SqlSugar -{ - public class DmSQLUpdateBuilder : UpdateBuilder - { - public override string SqlTemplateBatch - { - get - { - return @"UPDATE {1} {2} SET {0} FROM ${{0}} "; - } - } - public override string SqlTemplateJoin - { - get - { - return @" (VALUES - {0} - - ) AS T ({2}) WHERE {1} - "; - } - } - - public override string SqlTemplateBatchUnion - { - get - { - return ","; - } - } - - public override object FormatValue(object value) - { - if (value == null) - { - return "NULL"; - } - else - { - var type = 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); - return bytesString; - } - else if (type.IsEnum()) - { - return Convert.ToInt64(value); - } - else if (type == UtilConstants.BoolType) - { - return value.ObjToBool() ? "1" : "0"; - } - else if (type == UtilConstants.StringType || type == UtilConstants.ObjType) - { - return "'" + value.ToString().ToSqlFilter() + "'"; - } - else - { - return "'" + value.ToString() + "'"; - } - } - } - - protected override string TomultipleSqlString(List> groupList) - { - Check.Exception(PrimaryKeys == null || PrimaryKeys.Count == 0, " Update List need Primary key"); - int pageSize = 200; - int pageIndex = 1; - int totalRecord = groupList.Count; - int pageCount = (totalRecord + pageSize - 1) / pageSize; - StringBuilder batchUpdateSql = new StringBuilder(); - while (pageCount >= pageIndex) - { - StringBuilder updateTable = new StringBuilder(); - string setValues = string.Join(",", groupList.First().Where(it => it.IsPrimarykey == false && (it.IsIdentity == false || (IsOffIdentity && it.IsIdentity))).Select(it => - { - if (SetValues.IsValuable()) - { - var setValue = SetValues.Where(sv => sv.Key == Builder.GetTranslationColumnName(it.DbColumnName)); - if (setValue != null && setValue.Any()) - { - return setValue.First().Value; - } - } - var result = string.Format("{0}=T.{0}", Builder.GetTranslationColumnName(it.DbColumnName)); - return result; - })); - string tempColumnValue = string.Join(",", groupList.First().Select(it => - { - if (SetValues.IsValuable()) - { - var setValue = SetValues.Where(sv => sv.Key == Builder.GetTranslationColumnName(it.DbColumnName)); - if (setValue != null && setValue.Any()) - { - return setValue.First().Value; - } - } - var result = Builder.GetTranslationColumnName(it.DbColumnName); - return result; - })); - batchUpdateSql.AppendFormat(SqlTemplateBatch.ToString(), setValues, GetTableNameStringNoWith, TableWithString); - int i = 0; - var tableColumnList = this.Context.DbMaintenance.GetColumnInfosByTableName(GetTableNameStringNoWith); - - foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList()) - { - var isFirst = i == 0; - if (!isFirst) - { - updateTable.Append(SqlTemplateBatchUnion); - } - updateTable.Append("\r\n (" + string.Join(",", columns.Select(it => - { - var columnInfo = tableColumnList.FirstOrDefault(x => x.DbColumnName.Equals(it.DbColumnName, StringComparison.OrdinalIgnoreCase)); - var dbType = columnInfo?.DataType; - if (dbType == null) { - var typeName = it.PropertyType.Name.ToLower(); - if (typeName == "int32") - typeName = "int"; - if (typeName == "int64") - typeName = "long"; - if (typeName == "int16") - typeName = "short"; - - var isAnyType = PostgreSQLDbBind.MappingTypesConst.Where(x => x.Value.ToString().ToLower() == typeName).Any(); - if (isAnyType) - { - dbType = PostgreSQLDbBind.MappingTypesConst.Where(x => x.Value.ToString().ToLower() == typeName).FirstOrDefault().Key; - } - else { - dbType = "varchar"; - } - } - return string.Format("CAST({0} AS {1})", FormatValue(it.Value), dbType); - - })) + ")"); - ++i; - } - pageIndex++; - updateTable.Append("\r\n"); - string whereString = null; - if (this.WhereValues.HasValue()) - { - foreach (var item in WhereValues) - { - var isFirst = whereString == null; - whereString += (isFirst ? null : " AND "); - whereString += item; - } - } - else if (PrimaryKeys.HasValue()) - { - foreach (var item in PrimaryKeys) - { - var isFirst = whereString == null; - whereString += (isFirst ? null : " AND "); - whereString += string.Format("{0}.{1}=T.{1}", GetTableNameStringNoWith, Builder.GetTranslationColumnName(item)); - } - } - var format = string.Format(SqlTemplateJoin, updateTable, whereString, tempColumnValue); - batchUpdateSql.Replace("${0}", format); - batchUpdateSql.Append(";"); - } - return batchUpdateSql.ToString(); - } - } -} diff --git a/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmUpdateBuilder.cs b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmUpdateBuilder.cs new file mode 100644 index 000000000..247ac6045 --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Dm/SqlBuilder/DmUpdateBuilder.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public class DmUpdateBuilder : UpdateBuilder + { + protected override string TomultipleSqlString(List> groupList) + { + StringBuilder sb = new StringBuilder(); + int i = 0; + sb.AppendLine(string.Join("\r\n", groupList.Select(t => + { + var updateTable = string.Format("UPDATE {0} SET", base.GetTableNameStringNoWith); + var setValues = string.Join(",", t.Where(s => !s.IsPrimarykey).Select(m => GetOracleUpdateColums(i, m)).ToArray()); + var pkList = t.Where(s => s.IsPrimarykey).ToList(); + List whereList = new List(); + foreach (var item in pkList) + { + var isFirst = pkList.First() == item; + var whereString = ""; + whereString += GetOracleUpdateColums(i, item); + whereList.Add(whereString); + } + i++; + return string.Format("{0} {1} WHERE {2};", updateTable, setValues, string.Join("AND", whereList)); + }).ToArray())); + return sb.ToString(); + } + + private string GetOracleUpdateColums(int i, DbColumnInfo m) + { + return string.Format("\"{0}\"={1}", m.DbColumnName.ToUpper(), FormatValue(i, m.DbColumnName, m.Value)); + } + + public object FormatValue(int i, string name, object value) + { + 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.IsEnum()) + { + return Convert.ToInt64(value); + } + else if (type == UtilConstants.ByteArrayType) + { + var parameterName = this.Builder.SqlParameterKeyWord + name + i; + this.Parameters.Add(new SugarParameter(parameterName, value)); + return parameterName; + } + else if (type == UtilConstants.BoolType) + { + return value.ObjToBool() ? "1" : "0"; + } + else if (type == UtilConstants.StringType || type == UtilConstants.ObjType) + { + return "'" + value.ToString().ToSqlFilter() + "'"; + } + else + { + return "'" + value.ToString() + "'"; + } + } + } + } +} diff --git a/Src/Asp.Net/SqlSugar/SqlSugar.csproj b/Src/Asp.Net/SqlSugar/SqlSugar.csproj index 148bbc089..af6b8333a 100644 --- a/Src/Asp.Net/SqlSugar/SqlSugar.csproj +++ b/Src/Asp.Net/SqlSugar/SqlSugar.csproj @@ -149,19 +149,19 @@ - + - + - + @@ -335,9 +335,7 @@ - - - +