diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Config.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Config.cs new file mode 100644 index 000000000..b0427b911 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Config.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Config + { + public static string ConnectionString = "PORT=5432;DATABASE=SqlSugar4XTest;HOST=localhost;PASSWORD=haosql;USER ID=postgres"; + public static string ConnectionString2 = "PORT=5432;DATABASE=SqlSugar4XTest;HOST=localhost;PASSWORD=haosql;USER ID=postgres"; + public static string ConnectionString3 = "PORT=5432;DATABASE=SqlSugar4XTest;HOST=localhost;PASSWORD=haosql;USER ID=postgres"; + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/1_Query.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/1_Query.cs new file mode 100644 index 000000000..a1f50c462 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/1_Query.cs @@ -0,0 +1,603 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Demo +{ + public class Query : DemoBase + { + + public static void Init() + { + Easy(); + Page(); + Where(); + Join(); + Funs(); + Select(); + Ado(); + Group(); + Sqlable(); + Tran(); + StoredProcedure(); + Enum(); + Simple(); + Async(); + Subqueryable(); + SqlQueryable(); + } + + private static void SqlQueryable() + { + var db = GetInstance(); + var list = db.SqlQueryable("select * from student").ToPageList(1, 2); + } + + private static void Subqueryable() + { + var db = GetInstance(); + var i = 0; + + + var sumflat2num = db.Queryable((s1, s2) => + new object[] { JoinType.Left, s1.Id == s2.Id }) + + .Select((s1, s2) => new Student + { Id = SqlFunc.IsNull(SqlFunc.AggregateSum(SqlFunc.IIF(s1.Id ==1, s1.Id, s1.Id * -1)), 0) }) + .First(); + + var getAll11 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Max(s=>s.Id)==i).ToList(); + var getAll12 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Max(s => s.Id) == 1).ToList(); + var getAll7 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Any()).ToList(); + + var getAll9 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Count()==1).ToList(); + + var getAll10 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).OrderBy(s=>s.Id).Select(s=>s.Id) == 1).ToList(); + var getAll14 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).OrderByDesc(s => s.Id).Select(s => s.Id) == 1).ToList(); + + var getAll8= db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Where(s=>s.Name==it.Name).NotAny()).ToList(); + + var getAll1 = db.Queryable().Where(it => it.Id == SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Select(s => s.Id)).ToList(); + + var getAll2 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.Id==sc.Id + }) + .Where(st => st.Id == SqlFunc.Subqueryable().Where(s => s.Id == st.Id).Select(s => s.Id)) + .ToList(); + + var getAll3 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.Id==sc.Id + }) + .Select(st => + new + { + name = st.Name, + id = SqlFunc.Subqueryable().Where(s => s.Id == st.Id).Select(s => s.Id) + }) + .ToList(); + + var getAll4 = db.Queryable().Select(it => + new + { + name = it.Name, + id = SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Select(s => s.Id) + }).ToList(); + + var getAll5 = db.Queryable().Select(it => + new Student + { + Name = it.Name, + Id = SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Select(s => s.Id) + }).ToList(); + + var getAll6 = db.Queryable().Select(it => + new + { + name = it.Name, + id = SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Sum(s => (int)s.SchoolId) + }).ToList(); + + var getAll66 = db.Queryable().Select(it => + new + { + name = it.Name, + id = SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Sum(s =>s.SchoolId.Value) + }).ToList(); + + var getAll666 = db.Queryable().Select(it => + new + { + name = it.Name, + id = SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Min(s => s.Id) + }).ToList(); + + } + + private static void Async() + { + var db = GetInstance(); + var list = db.Queryable().Where(it => it.Id == 1).SingleAsync(); + list.Wait(); + + var list2 = db.Queryable().SingleAsync(it => it.Id == 1); + list2.Wait(); + + var list3 = db.Queryable().Where(it => it.Id == 1).ToListAsync(); + list3.Wait(); + + var list4 = db.Queryable().Where(it => it.Id == 1).ToPageListAsync(1, 2); + list4.Wait(); + } + + private static void Simple() + { + //SqlSugarClient + var db = GetInstance(); + var student1 = db.Queryable().InSingle(1); + + //get SimpleClient + var sdb = db.SimpleClient; + var student2 = sdb.GetById(1); + sdb.DeleteById(1); + sdb.Insert(new Student() { Name = "xx" }); + sdb.Update(it => new Student { Name = "newvalue" }, it => it.Id == 1);//only update name where id=1 + sdb.Update(new Student() { Name = "newavalue", Id = 1 });//update all where id=1 + + //SimpleClient Get SqlSugarClient + var student3 = sdb.FullClient.Queryable().InSingle(1); + + } + + private static void StoredProcedure() + { + var db = GetInstance(); + //1. no result + db.Ado.UseStoredProcedure(() => + { + string spName = "sp_help"; + var getSpReslut = db.Ado.SqlQueryDynamic(spName, new { objname = "student" }); + }); + + //2. has result + var result = db.Ado.UseStoredProcedure(() => + { + string spName = "sp_help"; + return db.Ado.SqlQueryDynamic(spName, new { objname = "student" }); + }); + + //2. has output + object outPutValue; + var outputResult = db.Ado.UseStoredProcedure(() => + { + string spName = "sp_school"; + var p1 = new SugarParameter("@p1", "1"); + var p2 = new SugarParameter("@p2", null, true);//isOutput=true + var dbResult = db.Ado.SqlQueryDynamic(spName, new SugarParameter[] { p1, p2 }); + outPutValue = p2.Value; + return dbResult; + }); + + + //3 + var dt = db.Ado.UseStoredProcedure().GetDataTable("sp_school", new { p1 = 1, p2 = 2 }); + + + var p11 = new SugarParameter("@p1", "1"); + var p22 = new SugarParameter("@p2", null, true);//isOutput=true + //4 + var dt2 = db.Ado.UseStoredProcedure().SqlQuery("sp_school", p11, p22); + } + private static void Tran() + { + var db = GetInstance(); + var x = db.Insertable(new Student() { CreateTime = DateTime.Now, Name = "tran" }).ExecuteCommand(); + //1. no result + var result = db.Ado.UseTran(() => + { + + var beginCount = db.Queryable().ToList(); + db.Ado.ExecuteCommand("delete student"); + var endCount = db.Queryable().Count(); + throw new Exception("error haha"); + }); + var count = db.Queryable().Count(); + + //2 has result + var result2 = db.Ado.UseTran>(() => + { + return db.Queryable().ToList(); + }); + + //3 use try + try + { + db.Ado.BeginTran(); + + db.Ado.CommitTran(); + } + catch (Exception) + { + db.Ado.RollbackTran(); + throw; + } + + + + //async tran + var asyncResult = db.Ado.UseTranAsync(() => + { + + var beginCount = db.Queryable().ToList(); + db.Ado.ExecuteCommand("delete student"); + var endCount = db.Queryable().Count(); + throw new Exception("error haha"); + }); + asyncResult.Wait(); + var asyncCount = db.Queryable().Count(); + + //async + var asyncResult2 = db.Ado.UseTranAsync>(() => + { + return db.Queryable().ToList(); + }); + asyncResult2.Wait(); + } + private static void Group() + { + var db = GetInstance(); + var list = db.Queryable() + .GroupBy(it => it.Name) + .GroupBy(it => it.Id).Having(it => SqlFunc.AggregateAvg(it.Id) > 0) + .Select(it => new { idAvg = SqlFunc.AggregateAvg(it.Id), name = it.Name }).ToList(); + + + var list2 = db.Queryable() + .GroupBy(it => new { it.Id, it.Name }).Having(it => SqlFunc.AggregateAvg(it.Id) > 0) + .Select(it => new { idAvg = SqlFunc.AggregateAvg(it.Id), name = it.Name }).ToList(); + //SQL: + //SELECT AVG([Id]) AS[idAvg], [Name] AS[name] FROM[Student] GROUP BY[Name],[Id] HAVING(AVG([Id]) > 0 ) + + // group id,name take first + var list3 = db.Queryable() + .PartitionBy(it => new { it.Id, it.Name }).Take(1).ToList(); + var list31 = db.Queryable() + .PartitionBy(it => new { it.Id, it.Name }).Take(1).Count(); + + int count = 0; + + var list4 = db.Queryable((st, sc) => st.SchoolId == sc.Id) + .PartitionBy(st => new { st.Name }).Take(2).OrderBy(st => st.Id, OrderByType.Desc).Select(st => st).ToPageList(1, 1000, ref count); + + //SqlFunc.AggregateSum(object thisValue) + //SqlFunc.AggregateAvg(TResult thisValue) + //SqlFunc.AggregateMin(object thisValue) + //SqlFunc.AggregateMax(object thisValue) + //SqlFunc.AggregateCount(object thisValue) + } + private static void Ado() + { + var db = GetInstance(); + db.Ado.BeginTran(); + var t1 = db.Ado.SqlQuery("select 'a'"); + var t2 = db.Ado.GetInt("select 1"); + var t3 = db.Ado.GetDataTable("select 1 as id"); + db.Ado.CommitTran(); + var t11 = db.Ado.SqlQuery("select * from student"); + //more + //db.Ado.GetXXX... + } + public static void Easy() + { + var db = GetInstance(); + var dbTime = db.GetDate(); + var getAll = db.Queryable().Select("*").ToList(); + var getAll2 = db.Queryable().ToList(); + var getRandomList = db.Queryable().OrderBy(it => SqlFunc.GetRandom()).ToList(); + var getAllOrder = db.Queryable().OrderBy(it => it.Id).OrderBy(it => it.Name, OrderByType.Desc).ToList(); + var getId = db.Queryable().Select(it => it.Id).ToList(); + var getNew = db.Queryable().Where(it => it.Id == 1).Select(it => new { id = SqlFunc.IIF(it.Id == 0, 1, it.Id), it.Name, it.SchoolId }).ToList(); + var getAllNoLock = db.Queryable().With(SqlWith.NoLock).ToList(); + 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 sum = db.Queryable().Select(it => it.SchoolId).ToList(); + var sum2 = db.Queryable((st, sc) => st.SchoolId == sc.Id).Sum((st, sc) => sc.Id); + var isAny = db.Queryable().Where(it => it.Id == -1).Any(); + var isAny2 = db.Queryable().Any(it => it.Id == -1); + var count = db.Queryable().Count(it => it.Id > 0); + // var date = db.Queryable().Where(it => it.CreateTime.Value.Date == DateTime.Now.Date).ToList(); + var getListByRename = db.Queryable().AS("Student").ToList(); + var in1 = db.Queryable().In(it => it.Id, new int[] { 1, 2, 3 }).ToList(); + var in2 = db.Queryable().In(new int[] { 1, 2, 3 }).ToList(); + int[] array = new int[] { 1, 2 }; + var in3 = db.Queryable().Where(it => SqlFunc.ContainsArray(array, it.Id)).ToList(); + var group = db.Queryable().GroupBy(it => it.Id) + .Having(it => SqlFunc.AggregateCount(it.Id) > 10) + .Select(it => new { id = SqlFunc.AggregateCount(it.Id) }).ToList(); + + var between = db.Queryable().Where(it => SqlFunc.Between(it.Id, 1, 20)).ToList(); + + // var getTodayList = db.Queryable().Where(it => SqlFunc.DateIsSame(it.CreateTime, DateTime.Now)).ToList(); + + var joinSql = db.Queryable("student", "s").OrderBy("id").Select("id,name").ToPageList(1, 2); + + // var getDay1List = db.Queryable().Where(it => it.CreateTime.Value.Hour == 1).ToList(); + //var getDateAdd = db.Queryable().Where(it => it.CreateTime.Value.AddDays(1) == DateTime.Now).ToList(); + //var getDateIsSame = db.Queryable().Where(it => SqlFunc.DateIsSame(DateTime.Now, DateTime.Now, DateType.Hour)).ToList(); + + var getSqlList = db.Queryable().AS("(select * from student) t").ToList(); + + + var getUnionAllList = db.UnionAll(db.Queryable().Where(it => it.Id == 1), db.Queryable().Where(it => it.Id == 2)).ToList(); + + var getUnionAllList2 = db.UnionAll(db.Queryable(), db.Queryable()).ToList(); + + //var getUnionAllList3= db.UnionAll(db.Queryable() + // .Select(it => new Student { Id =SqlFunc.ToInt32(1) ,Name=SqlFunc.ToString("2"), SchoolId = Convert.ToInt32(3) }) + // , db.Queryable() + // .Select(it => new Student { Id = SqlFunc.ToInt32(11) , Name = SqlFunc.ToString("22") , SchoolId=Convert.ToInt32(33)})) + // .Select(it=>new Student() { Id=SqlFunc.ToInt32(111), Name = SqlFunc.ToString("222") }).ToList(); + + //var test1 = db.Queryable((st, sc) => st.SchoolId == sc.Id).Where(st=>st.CreateTime>SqlFunc.GetDate()).Select((st, sc) => SqlFunc.ToInt64(sc.Id)).ToList(); + var test2 = db.Queryable((st, sc) => st.SchoolId == sc.Id) + .Where(st => + SqlFunc.IF(st.Id > 1) + .Return(st.Id) + .ElseIF(st.Id == 1) + .Return(st.SchoolId).End(st.Id) == 1).Select(st=>st).ToList(); + var test3 = db.Queryable().Select(it => it.Bool1).ToSql(); + var test4 = db.Queryable().Select(it => new { b=it.Bool1 }).ToSql(); + DateTime? result = DateTime.Now; + var test5 = db.Queryable().Where(it=>it.CreateTime> result.Value.Date).ToList(); + } + public static void Page() + { + var db = GetInstance(); + var pageIndex = 1; + var pageSize = 2; + var totalCount = 0; + //page + var page = db.Queryable().OrderBy(it => it.Id).ToPageList(pageIndex, pageSize, ref totalCount); + + //page join + var pageJoin = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).ToPageList(pageIndex, pageSize, ref totalCount); + + //top 5 + var top5 = db.Queryable().Take(5).ToList(); + + //skip5 + var skip5 = db.Queryable().Skip(5).ToList(); + } + public static void Where() + { + var db = GetInstance(); + //join + var list = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .Where((st, sc) => sc.Id == 1) + .Where((st, sc) => st.Id == 1) + .Where((st, sc) => st.Id == 1 && sc.Id == 2).ToList(); + + //SELECT [st].[Id],[st].[SchoolId],[st].[Name],[st].[CreateTime] FROM [Student] st + //Left JOIN School sc ON ( [st].[SchoolId] = [sc].[Id] ) + //WHERE ( [sc].[Id] = @Id0 ) AND ( [st].[Id] = @Id1 ) AND (( [st].[Id] = @Id2 ) AND ( [sc].[Id] = @Id3 )) + + + //Where If + string name = null; + string name2 = "sunkaixuan"; + var list2 = db.Queryable() + .WhereIF(!string.IsNullOrEmpty(name), it => it.Name == name) + .WhereIF(!string.IsNullOrEmpty(name2), it => it.Name == name2).ToList(); + + + + //join + var list3 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .WhereIF(false, (st, sc) => sc.Id == 1) + .WhereIF(false, (st, sc) => st.Id == 1).ToList(); + + + var list4 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .Select((st, sc) => new { id = st.Id, school = sc }).ToList(); + + + var list5 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).AS("STUDENT").AS("SCHOOL") +.Select((st, sc) => new { id = st.Id, school = sc }).ToList(); + + + var list6 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).AS("STUDENT").AS("SCHOOL") +.Select((st, sc) => new { id = st.Id, school = sc }).ToList(); + } + public static void Join() + { + var db = GetInstance(); + //join 2 + var list = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .Where(st => st.Name == "jack").ToList(); + + //join 3 + var list2 = db.Queryable((st, sc, st2) => new object[] { + JoinType.Left,st.SchoolId==sc.Id, + JoinType.Left,st.SchoolId==st2.Id + }) + .Where((st, sc, st2) => st2.Id == 1 || sc.Id == 1 || st.Id == 1).ToList(); + + //join return List + var list3 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).Select((st, sc) => new ViewModelStudent { Name = st.Name, SchoolId = sc.Id }).ToList(); + + //join Order By (order by st.id desc,sc.id desc) + var list4 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .OrderBy(st => st.Id, OrderByType.Desc) + .OrderBy((st, sc) => sc.Id, OrderByType.Desc) + .Select((st, sc) => new ViewModelStudent { Name = st.Name, SchoolId = sc.Id }).ToList(); + + + //join 2 + var list4_1 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id&& st.Name == "jack" + }).ToList(); + + + //The simple use of Join 2 table + var list5 = db.Queryable((st, sc) => st.SchoolId == sc.Id).Select((st, sc) => new { st.Name, st.Id, schoolName = sc.Name }).ToList(); + + //join 3 table + var list6 = db.Queryable((st, sc, sc2) => st.SchoolId == sc.Id && sc.Id == sc2.Id) + .Select((st, sc, sc2) => new { st.Name, st.Id, schoolName = sc.Name, schoolName2 = sc2.Name }).ToList(); + + //join 3 table page + var list7 = db.Queryable((st, sc, sc2) => st.SchoolId == sc.Id && sc.Id == sc2.Id) + .Select((st, sc, sc2) => new { st.Name, st.Id, schoolName = sc.Name, schoolName2 = sc2.Name }).ToPageList(1, 2); + + //join 3 table page + var list8 = db.Queryable((st, sc, sc2) => st.SchoolId == sc.Id && sc.Id == sc2.Id) + .OrderBy(st => st.Id) + .Select((st, sc, sc2) => new { st.Name, st.Id, schoolName = sc.Name, schoolName2 = sc2.Name }).ToPageList(1, 2); + + //In + var list9 = db.Queryable("it") + .OrderBy(it => it.Id) + .In(it => it.Id, db.Queryable().Where("it.id=schoolId").Select(it => it.Id)) + .ToList(); + //SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent] it WHERE [ID] + //IN (SELECT [Id] FROM [School] WHERE it.id=schoolId ) ORDER BY [ID] ASC + + var list10 = db.Queryable((st, sc) => st.SchoolId == sc.Id) + .In(st => st.Name, db.Queryable("sc2").Where("id=st.schoolid").Select(it => it.Name)) + .OrderBy(st => st.Id) + .Select(st => st) + .ToList(); + //SELECT st.* FROM [STudent] st ,[School] sc WHERE ( [st].[SchoolId] = [sc].[Id] ) AND [st].[Name] + //IN (SELECT [Name] FROM [School] sc2 WHERE id=st.schoolid ) ORDER BY [st].[ID] ASC + + var list11 = db.Queryable((st, sc) => st.SchoolId == sc.Id) + .In(st => st.Name, db.Queryable("sc2").Where(it => it.Id == 1).Where("id=st.schoolid").Select(it => it.Name)) + .OrderBy(st => st.Id) + .Select(st => st) + .ToList(); + + var subquery = db.Queryable().Where(it => it.Id == 1); + var subquery2 = db.Queryable(); + db.Queryable(subquery, subquery2, (st1, st2) => st1.Id == st2.Id).Select((st1,st2)=>new { + id=st1.Id, + name=st2.Name + }).ToList(); + } + public static void Funs() + { + var db = GetInstance(); + var t1 = db.Queryable().Where(it => SqlFunc.ToLower(it.Name) == SqlFunc.ToLower("JACK")).ToList(); + var t2 = db.Queryable().Where(it => SqlFunc.IsNull(it.Name,"nullvalue")=="nullvalue").ToList(); + var t3 = db.Queryable().Where(it => SqlFunc.MergeString("a",it.Name) == "nullvalue").ToList(); + //SELECT [Id],[SchoolId],[Name],[CreateTime] FROM [Student] WHERE ((LOWER([Name])) = (LOWER(@MethodConst0)) ) + + /***More Functions***/ + //SqlFunc.IsNullOrEmpty(object thisValue) + //SqlFunc.ToLower(object thisValue) + //SqlFunc.string ToUpper(object thisValue) + //SqlFunc.string Trim(object thisValue) + //SqlFunc.bool Contains(string thisValue, string parameterValue) + //SqlFunc.ContainsArray(object[] thisValue, string parameterValue) + //SqlFunc.StartsWith(object thisValue, string parameterValue) + //SqlFunc.EndsWith(object thisValue, string parameterValue) + //SqlFunc.Equals(object thisValue, object parameterValue) + //SqlFunc.DateIsSame(DateTime date1, DateTime date2) + //SqlFunc.DateIsSame(DateTime date1, DateTime date2, DateType dataType) + //SqlFunc.DateAdd(DateTime date, int addValue, DateType millisecond) + //SqlFunc.DateAdd(DateTime date, int addValue) + //SqlFunc.DateValue(DateTime date, DateType dataType) + //SqlFunc.Between(object value, object start, object end) + //SqlFunc.ToInt32(object value) + //SqlFunc.ToInt64(object value) + //SqlFunc.ToDate(object value) + //SqlFunc.ToString(object value) + //SqlFunc.ToDecimal(object value) + //SqlFunc.ToGuid(object value) + //SqlFunc.ToDouble(object value) + //SqlFunc.ToBool(object value) + //SqlFunc.Substring(object value, int index, int length) + //SqlFunc.Replace(object value, string oldChar, string newChar) + //SqlFunc.Length(object value) { throw new NotImplementedException(); } + //SqlFunc.AggregateSum(object thisValue) + //SqlFunc.AggregateAvg(TResult thisValue) + //SqlFunc.AggregateMin(object thisValue) + //SqlFunc.AggregateMax(object thisValue) + //SqlFunc.AggregateCount(object thisValue) + } + public static void Select() + { + var db = GetInstance(); + db.IgnoreColumns.Add("TestId", "Student"); + var s1 = db.Queryable().Where(it => it.Id == 136915).Single(); + var s2 = db.Queryable().Select(it => new { id = it.Id, w = new { x = it } }).ToList(); + var s3 = db.Queryable().Select(it => new { newid = it.Id }).ToList(); + var s4 = db.Queryable().Select(it => new { newid = it.Id, obj = it }).ToList(); + var s41 = db.Queryable().Select("*").ToList(); + var s5 = db.Queryable().Select(it => new ViewModelStudent2 { Student = it, Name = it.Name }).ToList(); + var s6 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .OrderBy(st => st.Id, OrderByType.Desc) + .OrderBy((st, sc) => sc.Id, OrderByType.Desc) + .Select((st, sc) => new { Name = st.Name, SchoolId = sc.Id }).ToList(); + + + var s7 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).Select((st, sc) => sc).ToList(); + + var s8 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .OrderBy((st, sc) => st.SchoolId) + .Select((st, sc) => sc) + .Take(1).ToList(); + + var s9 = db.Queryable().Select(it=>new Student() { Id=it.Id, TestId=1, Name=it.Name, CreateTime=it.CreateTime }).First(); + var s10 = db.Queryable().Select(it => new Student() { Id = it.Id}).First(); + + //auto fill + var s11 = db.Queryable((st,sc)=>st.SchoolId==sc.Id).Select().ToList(); + } + private static void Sqlable() + { + var db = GetInstance(); + var join3 = db.Queryable("Student", "st") + .AddJoinInfo("School", "sh", "sh.id=st.schoolid") + .Where("st.id>@id") + .AddParameters(new { id = 1 }) + .Select("st.*").ToList(); + //SELECT st.* FROM [Student] st Left JOIN School sh ON sh.id=st.schoolid WHERE st.id>@id + } + private static void Enum() + { + var db = GetInstance(); + var list = db.Queryable().AS("Student").Where(it => it.SchoolId == SchoolEnum.HarvardUniversity).ToList(); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/2_Update.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/2_Update.cs new file mode 100644 index 000000000..fe842df47 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/2_Update.cs @@ -0,0 +1,87 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Demo +{ + public class Update : DemoBase + { + public static void Init() + { + var db = GetInstance(); + var updateObj = new Student() { Id = 1, Name = "jack", SchoolId = 0, CreateTime = Convert.ToDateTime("2017-05-21 09:56:12.610") }; + var updateObjs = new List() { updateObj, new Student() { Id = 2, Name = "sun", SchoolId = 0 } }.ToArray(); + db.IgnoreColumns.Add("TestId", "Student"); + //db.MappingColumns.Add("id","dbid", "Student"); + + + //update reutrn Update Count + var t1 = db.Updateable(updateObj).ExecuteCommand(); + + //Only update Name + var t3 = db.Updateable(updateObj).UpdateColumns(it => new { it.Name }).ExecuteCommand(); + var t3_1 = db.Updateable(updateObj).UpdateColumns(it => it == "Name").ExecuteCommand(); + + + //Ignore Name and TestId + var t4 = db.Updateable(updateObj).IgnoreColumns(it => new { it.Name, it.TestId }).ExecuteCommand(); + + //Ignore Name and TestId + var t5 = db.Updateable(updateObj).IgnoreColumns(it => it == "Name" || it == "TestId").With(SqlWith.UpdLock).ExecuteCommand(); + + + //Use Lock + var t6 = db.Updateable(updateObj).With(SqlWith.UpdLock).ExecuteCommand(); + + //update List + var t7 = db.Updateable(updateObjs).ExecuteCommand(); + + //Re Set Value + var t8 = db.Updateable(updateObj) + .ReSetValue(it => it.Name == (it.Name + 1)).ExecuteCommand(); + + //Where By Expression + var t9 = db.Updateable(updateObj).Where(it => it.Id == 1).ExecuteCommand(); + + //Update By Expression Where By Expression + var t10 = db.Updateable() + .UpdateColumns(it => new Student() { Name = "a", CreateTime = DateTime.Now }) + .Where(it => it.Id == 11).ExecuteCommand(); + + //Rename + db.Updateable().AS("Student").UpdateColumns(it => new School() { Name = "jack" }).Where(it => it.Id == 1).ExecuteCommand(); + //Update Student set Name='jack' Where Id=1 + + //Column is null no update + db.Updateable(updateObj).Where(true).ExecuteCommand(); + + //sql + db.Updateable(updateObj).Where("id=@x",new { x="1"}).ExecuteCommand(); + db.Updateable(updateObj).Where("id","=",1).ExecuteCommand(); + var t12 = db.Updateable().AS("Student").UpdateColumns(it => new School() { Name = "jack" }).Where(it => it.Id == 1).ExecuteCommandAsync(); + t12.Wait(); + + //update one columns + var count = db.Updateable().UpdateColumns(it => it.SchoolId == it.SchoolId).Where(it => it.Id == it.Id+1).ExecuteCommand(); + + var count1 = db.Updateable() + .UpdateColumnsIF(false,it => it.SchoolId == it.SchoolId)//ignore + .UpdateColumnsIF(true, it => it.SchoolId == 2).//ok + Where(it => it.Id == it.Id + 1).ExecuteCommand(); + + + //update one columns + var count2 = db.Updateable().UpdateColumns(it => it.SchoolId == it.SchoolId+1).Where(it => it.Id == it.Id + 1).ExecuteCommand(); + + var dt = new Dictionary(); + dt.Add("id", 1); + dt.Add("name", null); + dt.Add("createTime", DateTime.Now); + var t66 = db.Updateable(dt).AS("student").With(SqlWith.UpdLock).ExecuteCommand(); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/3_Insert.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/3_Insert.cs new file mode 100644 index 000000000..4bcab57e8 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/3_Insert.cs @@ -0,0 +1,70 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Demo +{ + public class Insert:DemoBase + { + public static void Init() + { + var db = GetInstance(); + db.IgnoreColumns.Add("TestId", "Student"); + + var insertObj = new Student() { Name = "jack", CreateTime = Convert.ToDateTime("2010-1-1"), SchoolId = 1 }; + + //Insert reutrn Insert Count + var t2 = db.Insertable(insertObj).ExecuteCommand(); + + //Insert reutrn Identity Value + var t3 = db.Insertable(insertObj).ExecuteReturnIdentity(); + + //Insert reutrn Identity Value + var t31 = db.Insertable(insertObj).ExecuteReturnEntity(); + + //Only insert Name and SchoolId + var t4 = db.Insertable(insertObj).InsertColumns(it => new { it.Name, it.SchoolId }).ExecuteReturnIdentity(); + var t4_1 = db.Insertable(insertObj).InsertColumns(it => it=="Name"||it== "SchoolId").ExecuteReturnIdentity(); + + + //Ignore TestId + var t5 = db.Insertable(insertObj).IgnoreColumns(it => new { it.Name, it.TestId }).ExecuteReturnIdentity(); + + + //Ignore TestId + var t6 = db.Insertable(insertObj).IgnoreColumns(it => it == "Name" || it == "TestId").ExecuteReturnIdentity(); + + + //Use Lock + var t8 = db.Insertable(insertObj).With(SqlWith.UpdLock).ExecuteCommand(); + + + var insertObj2 = new Student() { Name = null, CreateTime = Convert.ToDateTime("2010-1-1") }; + var t9 = db.Insertable(insertObj2).Where(true/* Is insert null */, false/*off identity*/).ExecuteCommand(); + + //Insert List + var insertObjs = new List(); + for (int i = 0; i < 1000; i++) + { + insertObjs.Add(new Student() { Name = "name" + i }); + } + var t10 = db.Insertable(insertObjs.ToArray()).InsertColumns(it => new { it.Name }).ExecuteCommand(); + + var t11 = db.Insertable(insertObjs.ToArray()).ExecuteCommand(); + + + var t12 = db.Insertable(insertObj).IgnoreColumns(it => it == "Name" || it == "TestId").ExecuteReturnIdentityAsync(); + t12.Wait(); + + + var dt = new Dictionary(); + dt.Add("name", "1"); + dt.Add("CreateTime", null); + var t66 = db.Insertable(dt).AS("student").ExecuteReturnIdentity(); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/4_Delete.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/4_Delete.cs new file mode 100644 index 000000000..5ca74d226 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/4_Delete.cs @@ -0,0 +1,45 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Demo +{ + public class Delete:DemoBase + { + public static void Init() + { + var db = GetInstance(); + //by entity + var t1 = db.Deleteable().Where(new Student() { Id = 1 }).ExecuteCommand(); + + //use lock + var t2 = db.Deleteable().With(SqlWith.RowLock).ExecuteCommand(); + + + //by primary key + var t3 = db.Deleteable().In(1).ExecuteCommand(); + + //by primary key array + var t4 = db.Deleteable().In(new int[] { 1, 2 }).ExecuteCommand(); + var t41 = db.Deleteable().In(new int[] { 1, 2 }.Select(it=>it)).ExecuteCommand(); + var t42 = db.Deleteable().In(new int[] { 1, 2 }.AsEnumerable()).ExecuteCommand(); + + + //by exp key array + var t44 = db.Deleteable().In(it=>it.SchoolId,new int[] { 1, 2 }).ExecuteCommand(); + var t441 = db.Deleteable().In(it => it.SchoolId,new int[] { 1, 2 }.Select(it => it)).ExecuteCommand(); + var t442 = db.Deleteable().In(it => it.SchoolId,new int[] { 1, 2 }.AsEnumerable()).ExecuteCommand(); + var t443 = db.Deleteable().In(it => it.SchoolId, new int[] { 1, 2 }.ToList()).ExecuteCommand(); + + //by expression id>1 and id==1 + var t5 = db.Deleteable().Where(it => it.Id > 1).Where(it => it.Id == 1).ExecuteCommand(); + + var t6 = db.Deleteable().AS("student").Where(it => it.Id > 1).Where(it => it.Id == 1).ExecuteCommandAsync(); + t6.Wait(); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/5_CodeFirst.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/5_CodeFirst.cs new file mode 100644 index 000000000..f2482701d --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/5_CodeFirst.cs @@ -0,0 +1,59 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + [SugarTable("CodeTable", " table CodeTable")] + public class CodeTable + { + + + [SugarColumn(IsNullable =false ,IsPrimaryKey =true,IsIdentity =true,ColumnDescription ="XXhaha primary key!!")] + public int Id { get; set; } + [SugarColumn(Length = 21,OldColumnName = "Name2")] + public string Name{ get; set; } + public string IsOk { get; set; } + public Guid Guid { get; set; } + [SugarColumn(ColumnDataType ="int")] + public decimal Decimal { get; set; } + [SugarColumn(IsNullable = true)] + public DateTime? DateTime { get; set; } + [SugarColumn(IsNullable = true,OldColumnName = "Dob")] + public double? Dob2 { get; set; } + [SugarColumn(Length =11000)] + public string A1 { get; set; } + [SugarColumn(Length = 18,DecimalDigits=2)] + public decimal Dec { get; set; } + } + public class CodeTable2 { + public int Id { get; set; } + public string Name { get; set; } + [SugarColumn(IsIgnore =true)] + public string TestId { get; set; } + } + public class CodeFirst : DemoBase + { + public static void Init() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.PostgreSQL, + IsAutoCloseConnection = true, + InitKeyType = InitKeyType.Attribute + }); + + db.CodeFirst.InitTables(typeof(Student), typeof(School)); + + //Backup table + //db.CodeFirst.BackupTable().InitTables(typeof(CodeTable),typeof(CodeTable2)); + + //No backup table + // db.CodeFirst.SetStringDefaultLength(10).InitTables(typeof(CodeTable),typeof(CodeTable2)); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/5_DbFirst.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/5_DbFirst.cs new file mode 100644 index 000000000..7e79a7734 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/5_DbFirst.cs @@ -0,0 +1,72 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class DbFirst : DemoBase + { + public static void Init() + { + var db = GetInstance(); + //Create all class + db.DbFirst.CreateClassFile("c:\\Demo\\1"); + + //Create student calsss + db.DbFirst.Where("Student").CreateClassFile("c:\\Demo\\2"); + //Where(array) + + //Mapping name + db.MappingTables.Add("ClassStudent", "Student"); + db.MappingColumns.Add("NewId", "Id", "ClassStudent"); + db.DbFirst.Where("Student").CreateClassFile("c:\\Demo\\3"); + + //Remove mapping + db.MappingTables.Clear(); + + //Create class with default value + db.DbFirst.IsCreateDefaultValue().CreateClassFile("c:\\Demo\\4", "Demo.Models"); + + + //Mapping and Attribute + db.MappingTables.Add("ClassStudent", "Student"); + db.MappingColumns.Add("NewId", "Id", "ClassStudent"); + db.DbFirst.IsCreateAttribute().Where("Student").CreateClassFile("c:\\Demo\\5"); + + + //Remove mapping + db.MappingTables.Clear(); + db.MappingColumns.Clear(); + + //Custom format,Change old to new + 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\\6"); + } + } +} \ No newline at end of file diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/6_ComplexModel.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/6_ComplexModel.cs new file mode 100644 index 000000000..b5eecd86c --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/6_ComplexModel.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SqlSugar; +using OrmTest.Demo; + +namespace OrmTest.Demo +{ + public class ComplexModel : DemoBase + { + public static void Init() + { + var db = GetInstance(); + db.Insertable(new CMStudent() { SchoolId = 1, Name = "xx1" }).ExecuteCommand(); + var students = db.Queryable().ToList(); + if (students != null) + { + foreach (var item in students) + { + Console.WriteLine(item.SchoolName); + if (item.SchoolSingle != null) + { + Console.WriteLine(item.SchoolSingle.Name); + } + if (item.SchoolList != null) + { + Console.WriteLine(item.SchoolList.Count); + } + } + } + + db.Insertable(new CMStudent() { Name="xx" }).ExecuteCommand(); + } + } + + [SugarTable("Student")] + public class CMStudent : ModelContext + { + public int Id { get; set; } + public string Name { get; set; } + public int SchoolId { get; set; } + + [SugarColumn(IsIgnore = true)] + public string SchoolName + { + get + { + if (this.SchoolSingle != null) + return this.SchoolSingle.Name; + else + return null; + } + } + + [SugarColumn(IsIgnore = true)] + public CMSchool SchoolSingle + { + get + { + return base.CreateMapping().Single(it => it.Id == this.SchoolId); + } + } + + [SugarColumn(IsIgnore = true)] + public List SchoolList + { + get + { + return base.CreateMapping().Where(it => it.Id == this.SchoolId).ToList(); + } + } + } + + [SugarTable("School")] + public class CMSchool + { + public int Id { get; set; } + public string Name { get; set; } + } +} \ No newline at end of file diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/7_Filter.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/7_Filter.cs new file mode 100644 index 000000000..03cf32f76 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/7_Filter.cs @@ -0,0 +1,84 @@ +using OrmTest.Demo; +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class Filter : DemoBase + { + public static void Init() + { + + + //gobal filter + var db = GetInstance1(); + + var sql = db.Queryable().ToSql(); + //SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent] WHERE isDelete=0 + + var sql2 = db.Queryable((f, s) => new object[] { JoinType.Left, f.SchoolId == s.Id }).ToSql(); + //SELECT[f].[ID],[f].[SchoolId],[f].[Name],[f].[CreateTime] + //FROM[STudent] f Left JOIN School s ON([f].[SchoolId] = [s].[Id]) WHERE f.isDelete=0 + + + //Specify name filter + var sql3 = db.Queryable().Filter("query1").ToSql(); + //SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent] WHERE WHERE id>@id AND isDelete=0 + + + //Specify key filter and disabled global filter + string key = "query1"; + var sql4 = db.Queryable().Filter(key,true).ToSql(); + //SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent] WHERE WHERE id>@id + + var sql5 = db.Ado.GetInt("select {0}"); + //select 1 + } + + public static SqlSugarClient GetInstance1() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Config.ConnectionString, DbType = DbType.SqlServer, IsAutoCloseConnection = true }); + db.QueryFilter + .Add(new SqlFilterItem() + { + FilterValue = filterDb => + { + return new SqlFilterResult() { Sql = " isDelete=0" }; + }, + IsJoinQuery = false + }).Add(new SqlFilterItem() + { + FilterValue = filterDb => + { + return new SqlFilterResult() { Sql = " f.isDelete=0" }; + }, + IsJoinQuery = true + }) + .Add(new SqlFilterItem() + { + FilterName = "query1", + FilterValue = filterDb => + { + return new SqlFilterResult() { Sql = " id>@id", Parameters = new { id = 1 } }; + }, + IsJoinQuery = false + }); + + //Processing prior to execution of SQL + db.Ado.ProcessingEventStartingSQL = (sql, par) => + { + if (sql.Contains("{0}")) + { + sql = string.Format(sql, "1"); + } + return new KeyValuePair(sql,par); + }; + return db; + } + } + +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/8_JoinSql.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/8_JoinSql.cs new file mode 100644 index 000000000..8107f72c6 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/8_JoinSql.cs @@ -0,0 +1,123 @@ +using OrmTest.Demo; +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + /// + /// Secure string operations + /// + public class JoinSql : DemoBase + { + public static void Init() + { + Where(); + OrderBy(); + SelectMerge(); + ConditionalModel(); + JoinExp(); + Clone(); + } + + private static void Clone() + { + var db = GetInstance(); + var qy = db.Queryable().Where(it => 1 == 1); + + var list1 = qy.Clone().Where(it => it.Id == 1).ToList(); + var list2 = qy.Clone().Where(it => it.Id == 2).ToList(); + + + + var qy2 = db.Queryable((st,sc)=>new object[]{ + JoinType.Left,st.SchoolId==sc.Id + }).Where((st,sc)=>st.Id == 1); + + var join0 = qy2.Clone().Where((st, sc) => sc.Id == 222).Select(st=>st.Id).ToList(); + var join1 = qy2.Clone().Where((st,sc) => st.Id== 1111).ToList(); + var join2 = qy2.Clone().Where((st,sc)=>sc.Id==222).ToList(); + } + + private static void JoinExp() + { + var db = GetInstance(); + + var exp= Expressionable.Create() + .OrIF(1==1,it => it.Id == 11) + .And(it=>it.Id==1) + .AndIF(2==2,it => it.Id == 1) + .Or(it =>it.Name == "a1").ToExpression(); + var list=db.Queryable().Where(exp).ToList(); + } + + private static void ConditionalModel() + { + var db = GetInstance(); + List conModels = new List(); + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1 + conModels.Add(new ConditionalModel() { FieldName = "Student.id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1 + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Like, FieldValue = "1" });// 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" }), + new KeyValuePair ( WhereType.And,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" }) + } + }); + var student = db.Queryable().Where(conModels).ToList(); + } + + private static void SelectMerge() + { + var db = GetInstance(); + //page join + var pageJoin = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .Where(st => st.Id==1) + .Where(st => st.Id==2) + .Select((st, sc) => new { id = st.Id, name = sc.Name }) + .MergeTable().Where(XXX => XXX.id == 1).OrderBy("name asc").ToList();// Prefix, is, not, necessary, and take the columns in select + + } + private static void Where() + { + var db = GetInstance(); + //Parameterized processing + string value = "'jack';drop table Student"; + var list = db.Queryable().Where("name=@name", new { name = value }).ToList(); + //Nothing happened + } + + private static void OrderBy() + { + var db = GetInstance(); + //propertyName is valid + string propertyName = "Id"; + string dbColumnName = db.EntityMaintenance.GetDbColumnName(propertyName); + var list = db.Queryable().OrderBy(dbColumnName).ToList(); + + //propertyName is invalid + try + { + propertyName = "Id'"; + dbColumnName = db.EntityMaintenance.GetDbColumnName(propertyName); + var list2 = db.Queryable().OrderBy(dbColumnName).ToList(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/9_Aop.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/9_Aop.cs new file mode 100644 index 000000000..bb611497c --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/9_Aop.cs @@ -0,0 +1,87 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class Aop + { + + public static void Init() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Config.ConnectionString, DbType = DbType.PostgreSQL, IsAutoCloseConnection = true }); + + + db.Aop.OnLogExecuted = (sql, pars) => + { + Console.Write("time:" + db.Ado.SqlExecutionTime.ToString()); + }; + db.Aop.OnLogExecuting = (sql, pars) => + { + + }; + db.Aop.OnError = (exp) => + { + + }; + db.Aop.OnExecutingChangeSql = (sql, pars) => + { + return new KeyValuePair(sql, pars); + }; + + db.Queryable().ToList(); + + try + { + db.Queryable().AS(" ' ").ToList(); + } + catch (Exception) + { + + + } + + + ////diff log demo + + //db.Aop.OnDiffLogEvent = it => + //{ + // var editBeforeData = it.BeforeData; + // var editAfterData = it.AfterData; + // var sql = it.Sql; + // var parameter = it.Parameters; + // var data = it.BusinessData; + //}; + + + //var id = db.Insertable(new Student() { Name = "beforeName" }) + //.EnableDiffLogEvent(new { title="add student"}) + //.ExecuteReturnIdentity(); + + + //db.Updateable(new Student() + //{ + // Id = id, + // CreateTime = DateTime.Now, + // Name = "afterName", + // SchoolId = 2 + //}) + //.EnableDiffLogEvent(new { title = "update Student", Modular = 1, Operator = "admin" }) + //.ExecuteCommand(); + + + //db.Deleteable(id) + //.EnableDiffLogEvent(new { title = "delete student" }) + //.ExecuteCommand(); + + + ////primary key guid + // db.Insertable(new DataTestInfo2() { Bool1=true, Bool2=false, PK=Guid.NewGuid(), Text1="a" }) + //.EnableDiffLogEvent(new { title = "add DataTestInfo2" }) + //.ExecuteReturnIdentity(); + } + } +} \ No newline at end of file diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/A_MasterSlave.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/A_MasterSlave.cs new file mode 100644 index 000000000..a571f1fa2 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/A_MasterSlave.cs @@ -0,0 +1,44 @@ +using OrmTest.Demo; +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class MasterSlave : DemoBase + { + + public static void Init() + { + + for (int i = 0; i < 10; i++) + { + var db = GetMasterSlaveInstance(); + var list = db.Insertable(new Student() { Name="aa" }).ExecuteCommand(); // ConnectionString2 or ConnectionString3 + } + //db.Insertable(new Student() { Name = "masterTest" }).ExecuteCommand();// Config.ConnectionString + } + + public static SqlSugarClient GetMasterSlaveInstance() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.PostgreSQL, + IsAutoCloseConnection = true, + SlaveConnectionConfigs = new List() { + new SlaveConnectionConfig() { HitRate=10, ConnectionString=Config.ConnectionString2 } , + new SlaveConnectionConfig() { HitRate=10, ConnectionString=Config.ConnectionString2 } + } + }); + db.Aop.OnLogExecuting = (sql, pars) => + { + Console.WriteLine(db.Ado.Connection.ConnectionString); + }; + return db; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/B_SharedConnection.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/B_SharedConnection.cs new file mode 100644 index 000000000..d774d05f2 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/B_SharedConnection.cs @@ -0,0 +1,87 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class SharedConnection : DemoBase + { + public static void Init() + { + StudentDal studentDal = new StudentDal(); + SchoolDal schoolDal = new SchoolDal(); + + try + { + studentDal.BeginTran(); + + Console.WriteLine("school Count:"+ schoolDal.GetSchoolCount());//0 + + studentDal.AddStudent(new Student() { Name = "StudentTest" }); + schoolDal.AddSchool(new School() { Name = "SchoolTest" });//1 + + Console.WriteLine("school Count:" + schoolDal.GetSchoolCount()); + + throw new Exception("error"); + } + catch (Exception ex) + { + studentDal.RollbackTran(); + Console.WriteLine("school Count:" + schoolDal.GetSchoolCount());//0 + } + } + + + } + public class StudentDal : BaseDao + { + public void AddStudent(Student sudent) + { + db.Insertable(sudent).ExecuteCommand(); + } + } + public class SchoolDal : BaseDao + { + public void AddSchool(School school) + { + db.Insertable(school).ExecuteCommand(); + } + public int GetSchoolCount() + { + return db.Queryable().Count(); + } + } + + public class BaseDao + { + + public SqlSugar.SqlSugarClient db { get { return GetInstance(); } } + public void BeginTran() + { + db.Ado.BeginTran(); + } + public void CommitTran() + { + db.Ado.CommitTran(); + } + public void RollbackTran() + { + db.Ado.RollbackTran(); + } + public SqlSugarClient GetInstance() + { + SqlSugarClient db = new SqlSugarClient( + new ConnectionConfig() { + ConnectionString = Config.ConnectionString, + DbType = DbType.SqlServer, + IsAutoCloseConnection = false, + IsShardSameThread= true /*Shard Same Thread*/ + }); + + return db; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/CS_TeacherStudent.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/CS_TeacherStudent.cs new file mode 100644 index 000000000..272ae4df2 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/CS_TeacherStudent.cs @@ -0,0 +1,88 @@ +using System; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class CS_TeacherStudent + { + + /// + /// Desc:- + /// Default:(newid()) + /// Nullable:False + /// + public Guid tabId {get;set;} + + /// + /// Desc:教师Id + /// Default:- + /// Nullable:False + /// + public string teacherId {get;set;} + + /// + /// Desc:教师课程Id(对应TeacherCourse.tabId) + /// Default:- + /// Nullable:False + /// + public string teacherCourseId {get;set;} + + /// + /// Desc:教学头内的序号 + /// Default:- + /// Nullable:True + /// + public int? ordInTC {get;set;} + + /// + /// Desc:学号 + /// Default:- + /// Nullable:False + /// + public string stuId {get;set;} + + /// + /// Desc:学生姓名 + /// Default:- + /// Nullable:True + /// + public string stuName {get;set;} + + /// + /// Desc:性别 + /// Default:- + /// Nullable:True + /// + public string stuSex {get;set;} + + /// + /// Desc:所属院系Id + /// Default:- + /// Nullable:True + /// + public string deptId {get;set;} + + /// + /// Desc:所属班级Id + /// Default:- + /// Nullable:True + /// + public string classId {get;set;} + + /// + /// Desc:不能对应班级代码的班级名称时源班级名称 + /// Default:- + /// Nullable:True + /// + public string sclassName {get;set;} + + /// + /// Desc:- + /// Default:((1)) + /// Nullable:True + /// + public int? validFlag {get;set;} + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/C_ExtSqlFun.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/C_ExtSqlFun.cs new file mode 100644 index 000000000..f0b4c0580 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/C_ExtSqlFun.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SqlSugar; +using OrmTest.Models; + +namespace OrmTest.Demo +{ + public class ExtSqlFun : DemoBase + { + public static SqlSugarClient GetDb() + { + //Create ext method + var expMethods = new List(); + expMethods.Add(new SqlFuncExternal() + { + UniqueMethodName = "MyToString", + MethodValue = (expInfo, dbType, expContext) => + { + return string.Format("CAST({0} AS VARCHAR(MAX))", expInfo.Args[0].MemberName); + } + }); + + var config = new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.SqlServer, + IsAutoCloseConnection = true, + ConfigureExternalServices = new ConfigureExternalServices() + { + SqlFuncServices = expMethods//set ext method + } + }; + + SqlSugarClient db = new SqlSugarClient(config); + return db; + } + + public static string MyToString(T str) + { + throw new NotSupportedException("Can only be used in expressions"); + } + + public static void Init() + { + var db = GetDb(); + var list = db.Queryable().Where(it => MyToString(it.Id) == "1302583").ToList(); + var sql = db.Queryable().Where(it => MyToString(it.Id) == "1302583").ToSql(); + Console.WriteLine(sql); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/D_QueryableView.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/D_QueryableView.cs new file mode 100644 index 000000000..3aaabe9c7 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/D_QueryableView.cs @@ -0,0 +1,33 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class QueryableView : DemoBase + { + public static void Init() + { + var db = GetInstance(); + var q1 = db.Queryable((st,sc)=>new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).Select((st, sc) => new ViewModelStudent4() { Id=st.Id, Name=st.Name,SchoolName=sc.Name }); + + var q2 = db.Queryable(); + + + var innerJoinList = db.Queryable(q1, q2, (j1, j2) => j1.Id == j2.Id).Select((j1, j2) => j1).ToList();//inner join + + var leftJoinList = db.Queryable(q1, q2,JoinType.Left, (j1, j2) => j1.Id == j2.Id).Select((j1, j2) => j1).ToList();//left join + } + } + + public class ViewModelStudent4 { + public int Id { get; set; } + public string SchoolName { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/E_Attribute.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/E_Attribute.cs new file mode 100644 index 000000000..66c6cc57a --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/E_Attribute.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SqlSugar; +namespace OrmTest.Demo +{ + public class AttributeDemo : DemoBase + { + public static void Init() + { + var db = GetInstance(); + AttributeTest a = new AttributeTest() + { + Name = "attr" + }; + db.Insertable(a).AS("student").ExecuteCommand(); + var list = db.Queryable().AS("student").ToList(); + var list2 = db.Queryable().AS("student").Select(it => new AttributeTest() { Aid = it.Aid + 1,CreateTime=DateTime.Now,Name=it.Name }).ToList(); + var s = new AttributeTest2() { Aid = 1,AName="a", CreateTime=DateTime.Now }; + var count = db.Updateable(s).UpdateColumns(it=>new { it.CreateTime,it.AName }).Where(it=>it.Aid==100).ExecuteCommand(); + } + + public class AttributeTest + { + [SugarColumn(ColumnName = "Id")] + public int Aid { get; set; } + public string Name { get; set; } + [SugarColumn(IsOnlyIgnoreInsert = true)] + public DateTime CreateTime { get; set; } + } + [SugarTable("student")] + public class AttributeTest2 + { + [SugarColumn(ColumnName = "Id")] + public int Aid { get; set; } + [SugarColumn(ColumnName = "Name")] + public string AName { get; set; } + [SugarColumn(IsOnlyIgnoreInsert = true)] + public DateTime CreateTime { get; set; } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/F_VersionValidation.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/F_VersionValidation.cs new file mode 100644 index 000000000..ac6789891 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/F_VersionValidation.cs @@ -0,0 +1,119 @@ +using OrmTest.Demo; +using OrmTest.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class VersionValidation : DemoBase + { + public static void Init() + { + TimestampDemo(); + DateTimeDemo(); + } + + private static void TimestampDemo() + { + var db = GetInstance(); + try + { + + var data = new StudentVersion() + { + Id = db.Queryable().Select(it => it.Id).First(), + CreateTime = DateTime.Now, + Name = "", + }; + db.Updateable(data).IgnoreColumns(it => new { it.Timestamp }).ExecuteCommand(); + + var time = db.Queryable().Where(it => it.Id == data.Id).Select(it => it.Timestamp).Single(); + + data.Timestamp = time; + + //is ok + db.Updateable(data).IsEnableUpdateVersionValidation().IgnoreColumns(it => new { it.Timestamp }).ExecuteCommand(); + //updated Timestamp change + + //is error + db.Updateable(data).IsEnableUpdateVersionValidation().IgnoreColumns(it => new { it.Timestamp }).ExecuteCommand(); + + //IsEnableUpdateVersionValidation Types of support int or long or byte[](Timestamp) or Datetime + + } + catch (Exception ex) + { + if (ex is SqlSugar.VersionExceptions) + { + Console.Write(ex.Message); + } + else + { + + } + } + } + private static void DateTimeDemo() + { + var db = GetInstance(); + try + { + + var data = new StudentVersion2() + { + Id = db.Queryable().Select(it => it.Id).First(), + CreateTime = DateTime.Now, + Name = "", + }; + db.Updateable(data).ExecuteCommand(); + + var time = db.Queryable().Where(it => it.Id == data.Id).Select(it => it.CreateTime).Single(); + + data.CreateTime = time; + + //is ok + db.Updateable(data).IsEnableUpdateVersionValidation().ExecuteCommand(); + + + data.CreateTime = time.AddMilliseconds(-1); + //is error + db.Updateable(data).IsEnableUpdateVersionValidation().ExecuteCommand(); + + //IsEnableUpdateVersionValidation Types of support int or long or byte[](Timestamp) or Datetime + + } + catch (Exception ex) + { + if (ex is SqlSugar.VersionExceptions) + { + Console.Write(ex.Message); + } + else + { + + } + } + } + + [SqlSugar.SugarTable("Student")] + public class StudentVersion + { + public int Id { get; set; } + public string Name { get; set; } + public DateTime CreateTime { get; set; } + [SqlSugar.SugarColumn(IsEnableUpdateVersionValidation = true,IsOnlyIgnoreInsert=true)] + public byte[] Timestamp { get; set; } + } + + [SqlSugar.SugarTable("Student")] + public class StudentVersion2 + { + public int Id { get; set; } + public string Name { get; set; } + [SqlSugar.SugarColumn(IsEnableUpdateVersionValidation = true, IsOnlyIgnoreInsert = true)] + public DateTime CreateTime { get; set; } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/G_Mapper.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/G_Mapper.cs new file mode 100644 index 000000000..9915944e7 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/G_Mapper.cs @@ -0,0 +1,64 @@ +using OrmTest.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class Mapper : DemoBase + { + public static void Init() + { + var db = GetInstance(); + + //auto fill ViewModelStudent3 + var s11 = db.Queryable((st, sc) => st.SchoolId == sc.Id) + .Select().ToList(); + + + var s12 = db.Queryable((st, sc) => st.SchoolId == sc.Id).Select() + + .Mapper((it, cache) => + { + + var allSchools = cache.GetListByPrimaryKeys(vmodel => vmodel.SchoolId); + //sql select shool where id (in(ViewModelStudent3[0].SchoolId , ViewModelStudent3[1].SchoolId...) + + //Equal to allSchools + //var allSchools2= cache.Get(list => + // { + // var ids=list.Select(i => it.SchoolId).ToList(); + // return db.Queryable().In(ids).ToList(); + //});Complex writing metho + + + /*one to one*/ + //Good performance + it.School = allSchools.FirstOrDefault(i => i.Id == it.SchoolId); + + //Poor performance. + //it.School = db.Queryable().InSingle(it.SchoolId); + + + /*one to many*/ + it.Schools = allSchools.Where(i => i.Id == it.SchoolId).ToList(); + + + /*C# syntax conversion*/ + it.Name = it.Name == null ? "null" : it.Name; + + }).ToList(); + + + var s13 = db.Queryable((st, sc) => st.SchoolId == sc.Id).Select() + + .Mapper((it, cache) => + { + it.Schools = db.Queryable().Where(i => i.Id == it.SchoolId).ToList(); + }).ToList(); + + + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/H_ExtEntity.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/H_ExtEntity.cs new file mode 100644 index 000000000..f50d5698b --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/H_ExtEntity.cs @@ -0,0 +1,58 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + /// + /// mapping ef attribute + /// + public class ExtEntity: DemoBase + { + public static void Init() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { + ConnectionString = Config.ConnectionString, + DbType = DbType.SqlServer, + IsAutoCloseConnection = true, + ConfigureExternalServices=new ConfigureExternalServices() { + EntityService = (property, column) => { + if (property.Name == "xxx") {// by name ignore column + column.IsIgnore = true; + } + 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; + } + } + } + }); + + var sql=db.Queryable().ToList(); + var sql2 = db.Insertable(new StudentTest()).ExecuteCommand(); + } + + } + + [Table("student")]//default + public class StudentTest { + + [Key] + public string Id { get; set; } + public string xxx { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/PerformanceTest.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/PerformanceTest.cs new file mode 100644 index 000000000..3ac2b9286 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/PerformanceTest.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading; +namespace SyntacticSugar +{ + + public class PerformanceTest + { + private DateTime _beginTime; + private DateTime _endTime; + private ParamsModel _params; + private List _CharSource = new List(); + /// + ///设置执行次数(默认:1) + /// + public void SetCount(int count) + { + _params.RunCount = count; + } + /// + /// 设置线程模式(默认:false) + /// + /// true为多线程 + public void SetIsMultithread(bool isMul) + { + _params.IsMultithread = isMul; + } + + /// + /// 构造函数 + /// + public PerformanceTest() + { + _params = new ParamsModel() + { + RunCount = 1 + }; + } + + /// + /// 执行函数 + /// + /// + public void Execute(Action action, Action rollBack, string name = null) + { + List arr = new List(); + _beginTime = DateTime.Now; + for (int i = 0; i < _params.RunCount; i++) + { + if (_params.IsMultithread) + { + var thread = new Thread(new System.Threading.ThreadStart(() => + { + action(i); + })); + thread.Start(); + arr.Add(thread); + } + else + { + action(i); + } + } + if (_params.IsMultithread) + { + foreach (Thread t in arr) + { + while (t.IsAlive) + { + Thread.Sleep(10); + } + } + + } + + _CharSource.Add(new PerformanceTestChartModel() { Name = name, Time = GetTime(), CPU = GetCurrentProcessSize() }); + rollBack(string.Format("总共执行时间:{0}秒", GetTime())); + } + + private double GetTime() + { + _endTime = DateTime.Now; + double totalTime = ((_endTime - _beginTime).TotalMilliseconds / 1000.0); + return totalTime; + } + + public List GetChartSource() + { + return _CharSource; + } + private Double GetCurrentProcessSize() + { + Process processes = Process.GetCurrentProcess(); + var processesSize = (Double)(processes.WorkingSet64); + return processesSize / (1024 * 1024); + } + + private class ParamsModel + { + public int RunCount { get; set; } + public bool IsMultithread { get; set; } + } + public class PerformanceTestChartModel + { + public string Name { get; set; } + public double Time { get; set; } + public double CPU { get; set; } + } + } + + +} \ No newline at end of file diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/Z_DemoBase.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/Z_DemoBase.cs new file mode 100644 index 000000000..fc59f2852 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Demos/Z_DemoBase.cs @@ -0,0 +1,22 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class DemoBase + { + public static SqlSugarClient GetInstance() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Config.ConnectionString, DbType = DbType.PostgreSQL, IsAutoCloseConnection = true }); + db.Aop.OnLogExecuting = (sql, pars) => + { + Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); + Console.WriteLine(); + }; + return db; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/DataTestInfo.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/DataTestInfo.cs new file mode 100644 index 000000000..935aefaff --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/DataTestInfo.cs @@ -0,0 +1,135 @@ +using System; +using System.Linq; +using System.Text; + +namespace OrmTest.Models +{ + /// + /// + /// + public class DataTestInfo + { + public DataTestInfo(){ + + } + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public int Int1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public int? Int2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public string String {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public decimal Decimal1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public decimal? Decimal2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public DateTime Datetime1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public DateTime? Datetime2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public byte[] Image1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public byte[] Image2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public Guid Guid1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public Guid? Guid2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public decimal Money1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public decimal? Money2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public byte[] Varbinary1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public byte[] Varbinary2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public double Float1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public double? Float2 {get;set;} + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/DataTestInfo2.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/DataTestInfo2.cs new file mode 100644 index 000000000..8f425a4c1 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/DataTestInfo2.cs @@ -0,0 +1,44 @@ +using System; +using System.Linq; +using System.Text; + +namespace OrmTest.Models +{ + /// + /// + /// + public class DataTestInfo2 + { + public DataTestInfo2(){ + + } + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public Guid PK {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public bool Bool1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public bool? Bool2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public string Text1 {get;set;} + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/Enum.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/Enum.cs new file mode 100644 index 000000000..09102a410 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/Enum.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Models +{ + public enum SchoolEnum + { + HarvardUniversity = 0, + UniversityOfOxford = 1 + } + public class StudentEnum + { + public int Id { get; set; } + public SchoolEnum SchoolId { get; set; } + public string Name { get; set; } + public DateTime? CreateTime { get; set; } + [SqlSugar.SugarColumn(IsIgnore =true)] + public int TestId { get; set; } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/School.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/School.cs new file mode 100644 index 000000000..2420c2092 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/School.cs @@ -0,0 +1,18 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Models +{ + public class School + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + [SugarColumn(Length = 50)] + public string Name { get; set; } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/Student.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/Student.cs new file mode 100644 index 000000000..b28476e5b --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/Student.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SqlSugar; +using System.Linq.Expressions; + +namespace OrmTest.Models +{ + [SugarTable("STudent")] + public class Student + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true, ColumnName = "ID")] + public int Id { get; set; } + public int? SchoolId { get; set; } + [SugarColumn(Length =50)] + public string Name { get; set; } + public DateTime? CreateTime { get; set; } + [SugarColumn(IsIgnore=true)] + public int TestId { get; set; } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/ViewModelStudent.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/ViewModelStudent.cs new file mode 100644 index 000000000..3ef6abee4 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Models/ViewModelStudent.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Models +{ + public class ViewModelStudent:Student + { + + } + public class ViewModelStudent2 + { + public string Name { get; set; } + public Student Student { get; set; } + } + public class ViewModelStudent3: Student + { + public string SchoolName { get; set; } + public string School_Name { get; set; } + public string ScId { get; set; } + public School School { get; set; } + public List Schools { get; set; } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/PgSqlTest.csproj b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/PgSqlTest.csproj new file mode 100644 index 000000000..4709587b1 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/PgSqlTest.csproj @@ -0,0 +1,12 @@ + + + + Exe + netcoreapp2.1 + + + + + + + diff --git a/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Program.cs b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Program.cs new file mode 100644 index 000000000..705400590 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Program.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using System.Linq.Expressions; +using SqlSugar; +using OrmTest.Models; +using System.Data.SqlClient; + + +namespace OrmTest +{ + class Program + { + static void Main(string[] args) + { + + // Demo.CodeFirst.Init(); + // Demo.Aop.Init(); + Demo.Query.Init(); + Demo.MasterSlave.Init(); + Demo.SharedConnection.Init(); + Demo.ExtSqlFun.Init(); + Demo.QueryableView.Init(); + Demo.AttributeDemo.Init(); + Demo.Mapper.Init(); + Demo.ExtEntity.Init(); + + + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln b/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln index 9022a349f..8dfeb671e 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSeverTest.sln @@ -13,7 +13,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SqliteTest", "SqliteTest\Sq EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OracleTest", "OracleTest\OracleTest.csproj", "{3247B9CB-C92D-4AE3-8A35-3131AB2BD406}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NugetTest", "NugetTest\NugetTest.csproj", "{E76C6F9B-BA90-4A5A-94D9-D3D48CBB6AA3}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NugetTest", "NugetTest\NugetTest.csproj", "{E76C6F9B-BA90-4A5A-94D9-D3D48CBB6AA3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PgSqlTest", "PgSqlTest\PgSqlTest.csproj", "{B9005A73-5307-48FB-90EA-CC18FE6926E2}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -45,6 +47,10 @@ Global {E76C6F9B-BA90-4A5A-94D9-D3D48CBB6AA3}.Debug|Any CPU.Build.0 = Debug|Any CPU {E76C6F9B-BA90-4A5A-94D9-D3D48CBB6AA3}.Release|Any CPU.ActiveCfg = Release|Any CPU {E76C6F9B-BA90-4A5A-94D9-D3D48CBB6AA3}.Release|Any CPU.Build.0 = Release|Any CPU + {B9005A73-5307-48FB-90EA-CC18FE6926E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9005A73-5307-48FB-90EA-CC18FE6926E2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9005A73-5307-48FB-90EA-CC18FE6926E2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9005A73-5307-48FB-90EA-CC18FE6926E2}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/DependencyManagement.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/DependencyManagement.cs index c05280517..05ea9876b 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/DependencyManagement.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/DependencyManagement.cs @@ -50,7 +50,12 @@ namespace SqlSugar } } - internal static void TryOracle() + public static void PostgreSQL() + { + + } + + public static void TryOracle() { if (!IsTryOracle) { diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/Mapper.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/Mapper.cs index 2de6f1526..80e03f21b 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/Mapper.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Infrastructure/Mapper.cs @@ -103,6 +103,9 @@ namespace SqlSugar } } result = queryBuilder.GetSelectByItems(selectItems); + if (_context.CurrentConnectionConfig.DbType == DbType.PostgreSQL) { + result = result.ToLower(); + } return result; } } diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/OnlyCore/DataExtensions.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/OnlyCore/DataExtensions.cs index e436c3bc8..5280b19c4 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/OnlyCore/DataExtensions.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/OnlyCore/DataExtensions.cs @@ -1,5 +1,6 @@ using Microsoft.Data.Sqlite; using MySql.Data.MySqlClient; +using Npgsql; using Oracle.ManagedDataAccess.Client; using System; using System.Collections; @@ -908,4 +909,132 @@ namespace SqlSugar } } } + + /// + /// 数据填充器 + /// + public class NpgsqlDataAdapter : IDataAdapter + { + private NpgsqlCommand command; + private string sql; + private NpgsqlConnection _sqlConnection; + + /// + /// SqlDataAdapter + /// + /// + public NpgsqlDataAdapter(NpgsqlCommand command) + { + this.command = command; + } + + public NpgsqlDataAdapter() + { + + } + + /// + /// SqlDataAdapter + /// + /// + /// + public NpgsqlDataAdapter(string sql, NpgsqlConnection _sqlConnection) + { + this.sql = sql; + this._sqlConnection = _sqlConnection; + } + + /// + /// SelectCommand + /// + public NpgsqlCommand SelectCommand + { + get + { + if (this.command == null) + { + this.command = new NpgsqlCommand(this.sql, this._sqlConnection); + } + return this.command; + } + set + { + this.command = value; + } + } + + /// + /// Fill + /// + /// + public void Fill(DataTable dt) + { + if (dt == null) + { + dt = new DataTable(); + } + var columns = dt.Columns; + var rows = dt.Rows; + using (NpgsqlDataReader dr = command.ExecuteReader()) + { + for (int i = 0; i < dr.FieldCount; i++) + { + string name = dr.GetName(i).Trim(); + if (!columns.ContainsKey(name)) + columns.Add(new DataColumn(name, dr.GetFieldType(i))); + } + + while (dr.Read()) + { + DataRow daRow = new DataRow(); + for (int i = 0; i < columns.Count; i++) + { + if (!daRow.ContainsKey(columns[i].ColumnName)) + daRow.Add(columns[i].ColumnName, dr.GetValue(i)); + } + dt.Rows.Add(daRow); + } + } + + } + + /// + /// Fill + /// + /// + public void Fill(DataSet ds) + { + if (ds == null) + { + ds = new DataSet(); + } + using (NpgsqlDataReader dr = command.ExecuteReader()) + { + do + { + var dt = new DataTable(); + var columns = dt.Columns; + var rows = dt.Rows; + for (int i = 0; i < dr.FieldCount; i++) + { + string name = dr.GetName(i).Trim(); + if (!columns.ContainsKey(name)) + columns.Add(new DataColumn(name, dr.GetFieldType(i))); + } + + while (dr.Read()) + { + DataRow daRow = new DataRow(); + for (int i = 0; i < columns.Count; i++) + { + if (!daRow.ContainsKey(columns[i].ColumnName)) + daRow.Add(columns[i].ColumnName, dr.GetValue(i)); + } + dt.Rows.Add(daRow); + } + ds.Tables.Add(dt); + } while (dr.NextResult()); + } + } + } } \ No newline at end of file diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/CodeFirst/PostgreSQLCodeFirst.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/CodeFirst/PostgreSQLCodeFirst.cs new file mode 100644 index 000000000..20fea6ad5 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/CodeFirst/PostgreSQLCodeFirst.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public class PostgreSQLCodeFirst : CodeFirstProvider + { + public override void NoExistLogic(EntityInfo entityInfo) + { + var tableName = GetTableName(entityInfo); + Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); + List columns = new List(); + if (entityInfo.Columns.HasValue()) + { + foreach (var item in entityInfo.Columns) + { + DbColumnInfo dbColumnInfo = this.EntityColumnToDbColumn(entityInfo, tableName, item); + columns.Add(dbColumnInfo); + } + } + this.Context.DbMaintenance.CreateTable(tableName, columns,true); + } + protected override DbColumnInfo EntityColumnToDbColumn(EntityInfo entityInfo, string tableName, EntityColumnInfo item) + { + var propertyType = UtilMethods.GetUnderType(item.PropertyInfo); + var result = new DbColumnInfo() + { + TableId = entityInfo.Columns.IndexOf(item), + DbColumnName = item.DbColumnName.HasValue() ? item.DbColumnName : item.PropertyName, + IsPrimarykey = item.IsPrimarykey, + IsIdentity = item.IsIdentity, + TableName = tableName, + IsNullable = item.IsNullable, + DefaultValue = item.DefaultValue, + ColumnDescription = item.ColumnDescription, + Length = item.Length + }; + GetDbType(item, propertyType, result); + if (result.DataType.Equals("varchar", StringComparison.CurrentCultureIgnoreCase) && result.Length == 0) + { + result.Length = 1; + } + return result; + } + + protected override void ConvertColumns(List dbColumns) + { + foreach (var item in dbColumns) + { + if (item.DataType == "DateTime") + { + item.Length = 0; + } + } + } + + protected override void ChangeKey(EntityInfo entityInfo, string tableName, EntityColumnInfo item) + { + this.Context.DbMaintenance.UpdateColumn(tableName, EntityColumnToDbColumn(entityInfo, tableName, item)); + if (!item.IsPrimarykey) + this.Context.DbMaintenance.DropConstraint(tableName,null); + if (item.IsPrimarykey) + this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName); + } + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/DbBind/PostgreSQLDbBind.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/DbBind/PostgreSQLDbBind.cs new file mode 100644 index 000000000..871b87322 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/DbBind/PostgreSQLDbBind.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SqlSugar +{ + public class PostgreSQLDbBind : DbBindProvider + { + public override string GetPropertyTypeName(string dbTypeName) + { + dbTypeName = dbTypeName.ToLower(); + var propertyTypes = MappingTypes.Where(it => it.Value.ToString().ToLower() == dbTypeName || it.Key.ToLower() == dbTypeName); + if (propertyTypes == null) + { + return "other"; + } + else if (dbTypeName == "xml" || dbTypeName == "string") + { + return "string"; + } + if (dbTypeName == "byte[]") + { + return "byte[]"; + } + else if (propertyTypes == null || propertyTypes.Count() == 0) + { + Check.ThrowNotSupportedException(string.Format(" \"{0}\" Type NotSupported, DbBindProvider.GetPropertyTypeName error.", dbTypeName)); + return null; + } + else if (propertyTypes.First().Value == CSharpDataType.byteArray) + { + return "byte[]"; + } + else + { + return propertyTypes.First().Value.ToString(); + } + } + public override List> MappingTypes + { + get + { + var extService = this.Context.CurrentConnectionConfig.ConfigureExternalServices; + if (extService != null && extService.AppendDataReaderTypeMappings.HasValue()) + { + return extService.AppendDataReaderTypeMappings.Union(MappingTypesConst).ToList(); + } + else + { + return MappingTypesConst; + } + } + } + public static List> MappingTypesConst = new List>(){ + + new KeyValuePair("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("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("character varying",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("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("bit",CSharpDataType.byteArray), + new KeyValuePair("bit varying",CSharpDataType.byteArray), + new KeyValuePair("varbit",CSharpDataType.@byte), + + }; + public override List StringThrow + { + get + { + return new List() { "int32", "datetime", "decimal", "double", "byte" }; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/DbFirst/PostgreSQLDbFirst.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/DbFirst/PostgreSQLDbFirst.cs new file mode 100644 index 000000000..fe829d0b3 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/DbFirst/PostgreSQLDbFirst.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public class PostgreSQLDbFirst : DbFirstProvider + { + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/DbMaintenance/PostgreSQLDbMaintenance.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/DbMaintenance/PostgreSQLDbMaintenance.cs new file mode 100644 index 000000000..128f0ab6d --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/DbMaintenance/PostgreSQLDbMaintenance.cs @@ -0,0 +1,271 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public class PostgreSQLDbMaintenance : DbMaintenanceProvider + { + #region DML + 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; + } + } + 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"; + } + } + 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 = (SELECT viewname from pg_views + WHERE schemaname ='public')"; + } + } + #endregion + + #region DDL + protected override string AddPrimaryKeySql + { + get + { + return "ALTER TABLE {0} ADD PRIMARY KEY({2}) /*{1}*/"; + } + } + protected override string AddColumnToTableSql + { + get + { + return "ALTER TABLE {0} ADD COLUMN {1} {2}{3} {4} {5} {6}"; + } + } + protected override string AlterColumnToTableSql + { + get + { + return "alter table {0} ALTER COLUMN {1} {2}{3} {4} {5} {6}"; + } + } + protected override string BackupDataBaseSql + { + get + { + return "mysqldump.exe {0} -uroot -p > {1} "; + } + } + protected override string CreateTableSql + { + get + { + return "CREATE TABLE {0}(\r\n{1} $PrimaryKey)"; + } + } + protected override string CreateTableColumn + { + get + { + return "{0} {1}{2} {3} {4} {5}"; + } + } + protected override string TruncateTableSql + { + get + { + return "TRUNCATE TABLE {0}"; + } + } + protected override string BackupTableSql + { + get + { + return "create table {0} as (select * from {1} limit {2} offset 0)"; + } + } + protected override string DropTableSql + { + get + { + return "DROP TABLE {0}"; + } + } + protected override string DropColumnToTableSql + { + get + { + return "ALTER TABLE {0} DROP COLUMN {1}"; + } + } + protected override string DropConstraintSql + { + get + { + return "ALTER TABLE {0} DROP CONSTRAINT {1}"; + } + } + protected override string RenameColumnSql + { + get + { + return "ALTER TABLE {0} RENAME {1} TO {2}"; + } + } + #endregion + + #region Check + protected override string CheckSystemTablePermissionsSql + { + get + { + return "select 1 from information_schema.columns limit 1 offset 0"; + } + } + #endregion + + #region Scattered + protected override string CreateTableNull + { + get + { + return "DEFAULT NULL"; + } + } + protected override string CreateTableNotNull + { + get + { + return "NOT NULL"; + } + } + protected override string CreateTablePirmaryKey + { + get + { + return "PRIMARY KEY"; + } + } + protected override string CreateTableIdentity + { + get + { + return "serial"; + } + } + + 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 => ""; + + protected override string AddTableRemarkSql => "comment on {0} user is '{1}'"; + + protected override string DeleteTableRemarkSql => "comment on {0} user is ''"; + + protected override string IsAnyTableRemarkSql => ""; + #endregion + + #region Methods + public override bool CreateTable(string tableName, List columns, bool isCreatePrimaryKey = true) + { + if (columns.HasValue()) + { + foreach (var item in columns) + { + if (item.DbColumnName.Equals("GUID", StringComparison.CurrentCultureIgnoreCase) && item.Length == 0) + { + item.Length = 10; + } + } + } + string sql = GetCreateTableSql(tableName, columns); + string primaryKeyInfo = null; + if (columns.Any(it => it.IsPrimarykey) && isCreatePrimaryKey) + { + primaryKeyInfo = string.Format(", Primary key({0})", string.Join(",", columns.Where(it => it.IsPrimarykey).Select(it => this.SqlBuilder.GetTranslationColumnName(it.DbColumnName.ToLower())))); + + } + sql = sql.Replace("$PrimaryKey", primaryKeyInfo); + 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; + } + 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.ToLower(), isCache); + } + #endregion + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/Insertable/PostgreSQLInserttable.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/Insertable/PostgreSQLInserttable.cs new file mode 100644 index 000000000..03cc247e9 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/Insertable/PostgreSQLInserttable.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar +{ + public class PostgreSQLInserttable : InsertableProvider where T : class, new() + { + public override int ExecuteReturnIdentity() + { + InsertBuilder.IsReturnIdentity = true; + PreToSql(); + string sql = InsertBuilder.ToSqlString().Replace("$PrimaryKey", GetPrimaryKeys().FirstOrDefault()); + RestoreMapping(); + var result = Ado.GetScalar(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray()).ObjToInt(); + return result; + } + + public override long ExecuteReturnBigIdentity() + { + InsertBuilder.IsReturnIdentity = true; + PreToSql(); + string sql = InsertBuilder.ToSqlString().Replace("$PrimaryKey", GetPrimaryKeys().FirstOrDefault()); + RestoreMapping(); + var result = Convert.ToInt64(Ado.GetScalar(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.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/PostgreSQLProvider.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/PostgreSQLProvider.cs new file mode 100644 index 000000000..e9e7dc92e --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/PostgreSQLProvider.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Npgsql; + +namespace SqlSugar +{ + public partial class PostgreSQLProvider : AdoProvider + { + public PostgreSQLProvider() { } + public override IDbConnection Connection + { + get + { + if (base._DbConnection == null) + { + try + { + var npgsqlConnectionString = base.Context.CurrentConnectionConfig.ConnectionString; + base._DbConnection = new NpgsqlConnection(npgsqlConnectionString); + } + catch (Exception ex) + { + Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message); + } + } + return base._DbConnection; + } + set + { + base._DbConnection = value; + } + } + + public override void BeginTran(string transactionName) + { + base.BeginTran(); + } + /// + /// Only SqlServer + /// + /// + /// + public override void BeginTran(IsolationLevel iso, string transactionName) + { + base.BeginTran(iso); + } + public override IDataAdapter GetAdapter() + { + return new NpgsqlDataAdapter(); + } + public override IDbCommand GetCommand(string sql, SugarParameter[] parameters) + { + NpgsqlCommand sqlCommand = new NpgsqlCommand(sql, (NpgsqlConnection)this.Connection); + sqlCommand.CommandType = this.CommandType; + sqlCommand.CommandTimeout = this.CommandTimeOut; + if (this.Transaction != null) + { + sqlCommand.Transaction = (NpgsqlTransaction)this.Transaction; + } + if (parameters.HasValue()) + { + IDataParameter[] ipars = ToIDbDataParameter(parameters); + sqlCommand.Parameters.AddRange((NpgsqlParameter[])ipars); + } + CheckConnection(); + return sqlCommand; + } + public override void SetCommandToAdapter(IDataAdapter dataAdapter, IDbCommand command) + { + ((NpgsqlDataAdapter)dataAdapter).SelectCommand = (NpgsqlCommand)command; + } + /// + /// if mysql return MySqlParameter[] pars + /// if sqlerver return SqlParameter[] pars ... + /// + /// + /// + public override IDataParameter[] ToIDbDataParameter(params SugarParameter[] parameters) + { + if (parameters == null || parameters.Length == 0) return null; + NpgsqlParameter[] result = new NpgsqlParameter[parameters.Length]; + int index = 0; + foreach (var parameter in parameters) + { + if (parameter.Value == null) parameter.Value = DBNull.Value; + var sqlParameter = new NpgsqlParameter(); + sqlParameter.ParameterName = parameter.ParameterName; + sqlParameter.Size = parameter.Size; + sqlParameter.Value = parameter.Value; + sqlParameter.DbType = parameter.DbType; + sqlParameter.Direction = parameter.Direction; + if (sqlParameter.Direction == 0) + { + sqlParameter.Direction = ParameterDirection.Input; + } + result[index] = sqlParameter; + if (sqlParameter.Direction.IsIn(ParameterDirection.Output, ParameterDirection.InputOutput, ParameterDirection.ReturnValue)) + { + if (this.OutputParameters == null) this.OutputParameters = new List(); + this.OutputParameters.RemoveAll(it => it.ParameterName == sqlParameter.ParameterName); + this.OutputParameters.Add(sqlParameter); + } + ++index; + } + return result; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/Queryable/PostgreSqlQueryable.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/Queryable/PostgreSqlQueryable.cs new file mode 100644 index 000000000..c4b1de65f --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/Queryable/PostgreSqlQueryable.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar +{ + public class PostgreSQLQueryable : QueryableProvider + { + public override ISugarQueryable With(string withString) + { + return this; + } + + public override ISugarQueryable PartitionBy(string groupFileds) + { + this.GroupBy(groupFileds); + return this; + } + } + public class PostgreSQLQueryable : QueryableProvider + { + public new ISugarQueryable With(string withString) + { + return this; + } + } + public class PostgreSQLQueryable : QueryableProvider + { + + } + public class PostgreSQLQueryable : QueryableProvider + { + + } + public class PostgreSQLQueryable : QueryableProvider + { + + } + public class PostgreSQLQueryable : QueryableProvider + { + + } + public class PostgreSQLQueryable : QueryableProvider + { + + } + public class PostgreSqlQueryable : QueryableProvider + { + + } + public class PostgreSQLQueryable : QueryableProvider + { + + } + public class PostgreSQLQueryable : QueryableProvider + { + + } + public class PostgreSQLQueryable : QueryableProvider + { + + } + public class PostgreSQLQueryable : QueryableProvider + { + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLBuilder.cs new file mode 100644 index 000000000..41584393a --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLBuilder.cs @@ -0,0 +1,78 @@ +using System; +using System.Linq; +using System.Text.RegularExpressions; + +namespace SqlSugar +{ + public class PostgreSQLBuilder : 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 override string GetNoTranslationColumnName(string name) + { + return name.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() + SqlTranslationRight : SqlTranslationLeft + mappingInfo.DbColumnName.ToLower() + 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(".")) + { + return string.Join(".", name.ToLower().Split('.').Select(it => SqlTranslationLeft + it + SqlTranslationRight)); + } + else if (name.Contains("(")) + { + return name.ToLower(); + } + else + { + return SqlTranslationLeft + name.ToLower() + SqlTranslationRight; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLDeleteBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLDeleteBuilder.cs new file mode 100644 index 000000000..57f4ba33a --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLDeleteBuilder.cs @@ -0,0 +1,7 @@ +namespace SqlSugar +{ + public class PostgreSQLDeleteBuilder : DeleteBuilder + { + + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLExpressionContext.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLExpressionContext.cs new file mode 100644 index 000000000..5582c82c9 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLExpressionContext.cs @@ -0,0 +1,216 @@ +using System; +using System.Linq; +namespace SqlSugar +{ + public class PostgreSQLExpressionContext : ExpressionContext, ILambdaExpressions + { + public SqlSugarClient Context { get; set; } + public PostgreSQLExpressionContext() + { + base.DbMehtods = new PostgreSQLMethod(); + } + public override string SqlTranslationLeft + { + get + { + return "\""; + } + } + public override string SqlTranslationRight + { + get + { + return "\""; + } + } + public override string GetTranslationText(string name) + { + return SqlTranslationLeft + name.ToLower() + SqlTranslationRight; + } + public override string GetTranslationTableName(string entityName, bool isMapping = true) + { + Check.ArgumentNullException(entityName, string.Format(ErrorMessage.ObjNotExist, "Table Name")); + if (IsTranslationText(entityName)) return entityName; + isMapping = isMapping && this.MappingTables.HasValue(); + var isComplex = entityName.Contains(UtilConstants.Dot); + if (isMapping && isComplex) + { + var columnInfo = entityName.Split(UtilConstants.DotChar); + var mappingInfo = this.MappingTables.FirstOrDefault(it => it.EntityName.Equals(columnInfo.Last(), StringComparison.CurrentCultureIgnoreCase)); + if (mappingInfo != null) + { + columnInfo[columnInfo.Length - 1] = mappingInfo.EntityName; + } + return string.Join(UtilConstants.Dot, columnInfo.Select(it => GetTranslationText(it))); + } + else if (isMapping) + { + var mappingInfo = this.MappingTables.FirstOrDefault(it => it.EntityName.Equals(entityName, StringComparison.CurrentCultureIgnoreCase)); + return SqlTranslationLeft + (mappingInfo == null ? entityName : mappingInfo.DbTableName) + SqlTranslationRight; + } + else if (isComplex) + { + return string.Join(UtilConstants.Dot, entityName.Split(UtilConstants.DotChar).Select(it => GetTranslationText(it))); + } + else + { + return GetTranslationText(entityName); + } + } + public override string GetTranslationColumnName(string columnName) + { + Check.ArgumentNullException(columnName, string.Format(ErrorMessage.ObjNotExist, "Column Name")); + if (columnName.Substring(0, 1) == this.SqlParameterKeyWord) + { + return columnName; + } + if (IsTranslationText(columnName)) return columnName; + if (columnName.Contains(UtilConstants.Dot)) + { + return string.Join(UtilConstants.Dot, columnName.Split(UtilConstants.DotChar).Select(it => GetTranslationText(it))); + } + else + { + return GetTranslationText(columnName); + } + } + public override string GetDbColumnName(string entityName, string propertyName) + { + if (this.MappingColumns.HasValue()) + { + var mappingInfo = this.MappingColumns.SingleOrDefault(it => it.EntityName == entityName && it.PropertyName == propertyName); + return (mappingInfo == null ? propertyName : mappingInfo.DbColumnName).ToLower(); + } + else + { + return propertyName.ToLower(); + } + } + } + public class PostgreSQLMethod : DefaultDbMethod, IDbMethods + { + public override string DateValue(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" {0}({1}) ", parameter2.MemberValue, parameter.MemberName); + } + + public override string Contains(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ({0} like concat('%',{1},'%')) ", parameter.MemberName, parameter2.MemberName ); + } + + public override string StartsWith(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ({0} like concat({1},'%')) ", parameter.MemberName, parameter2.MemberName); + } + + public override string EndsWith(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ({0} like concat('%',{1}))", parameter.MemberName,parameter2.MemberName); + } + + public override string DateIsSameDay(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" (date_part('day',{0}-{1})=0) ", parameter.MemberName, parameter2.MemberName); ; + } + + public override string DateIsSameByType(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var parameter3 = model.Args[2]; + return string.Format(" (date_part('{2}',{0}-{1})=0) ", parameter.MemberName, parameter2.MemberName, parameter3.MemberValue); + } + + public override string DateAddByType(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var parameter3 = model.Args[2]; + return string.Format(" (DATE_ADD({1} , INTERVAL {2} {0})) ", parameter3.MemberValue, parameter.MemberName, parameter2.MemberName); + } + + public override string DateAddDay(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" (DATE_ADD({1} INTERVAL {0} day)) ", parameter.MemberName, parameter2.MemberName); + } + + public override string ToInt32(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS SIGNED)", parameter.MemberName); + } + + public override string ToInt64(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS SIGNED)", parameter.MemberName); + } + + public override string ToString(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS VARCHAR)", parameter.MemberName); + } + + public override string ToGuid(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS VARCHAR)", parameter.MemberName); + } + + public override string ToDouble(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS DECIMAL(18,4))", parameter.MemberName); + } + + public override string ToBool(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS SIGNED)", parameter.MemberName); + } + + public override string ToDecimal(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS DECIMAL(18,4))", parameter.MemberName); + } + + public override string Length(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" LENGTH({0})", parameter.MemberName); + } + public override string MergeString(params string[] strings) + { + return " concat("+string.Join(",", strings).Replace("+", "") + ") "; + } + public override string IsNull(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter1 = model.Args[1]; + return string.Format("(CASE WHEN {0} IS NULL THEN {1} ELSE {0} END)", parameter.MemberName, parameter1.MemberName); + } + public override string GetDate() + { + return "NOW()"; + } + public override string GetRandom() + { + return "RANDOM()"; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLInsertBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLInsertBuilder.cs new file mode 100644 index 000000000..db2f10e13 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLInsertBuilder.cs @@ -0,0 +1,93 @@ +using System; +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public class PostgreSQLInsertBuilder : InsertBuilder + { + public override string SqlTemplate + { + get + { + if (IsReturnIdentity) + { + return @"INSERT INTO {0} + ({1}) + VALUES + ({2}) returning $PrimaryKey"; + } + else + { + return @"INSERT INTO {0} + ({1}) + VALUES + ({2}) ;"; + + } + } + } + public override string SqlTemplateBatch => "INSERT INTO {0} ({1})"; + public override string SqlTemplateBatchUnion => " VALUES "; + + public override string SqlTemplateBatchSelect => " {0} "; + + public override 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) + { + return string.Format(SqlTemplateBatchSelect, "NULL"); + } + return string.Format(SqlTemplateBatchSelect, "'" + value + "'"); + })) + "),"); + ++i; + } + pageIndex++; + batchInsetrSql.Remove(batchInsetrSql.Length - 1,1).Append("\r\n;\r\n"); + } + return batchInsetrSql.ToString(); + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLQueryBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLQueryBuilder.cs new file mode 100644 index 000000000..5f4b4674c --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLQueryBuilder.cs @@ -0,0 +1,93 @@ +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace SqlSugar +{ + public partial class PostgreSQLQueryBuilder : 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 + { + get + { + string result = string.Empty; + if (this.SelectValue == null || this.SelectValue is string) + { + result = GetSelectValueByString(); + } + else + { + result = GetSelectValueByExpression(); + } + if (this.SelectType == ResolveExpressType.SelectMultiple) + { + this.SelectCacheKey = this.SelectCacheKey + string.Join("-", this.JoinQueryInfos.Select(it => it.TableName)); + } + return result; + } + } + + #endregion + } +} diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLUpdateBuilder.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLUpdateBuilder.cs new file mode 100644 index 000000000..276e4b94a --- /dev/null +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLUpdateBuilder.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public class PostgreSQLUpdateBuilder : 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 => string.Format("CAST({0} AS {1})", FormatValue(it.Value), tableColumnList.FirstOrDefault(x => x.DbColumnName.Equals(it.DbColumnName, StringComparison.OrdinalIgnoreCase))?.DataType))) + ")"); + ++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.NetCore2/SqlSeverTest/SqlSugar/SqlSugar.csproj b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/SqlSugar.csproj index 02dec07b4..ebd605470 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/SqlSugar.csproj +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/SqlSugar.csproj @@ -14,6 +14,7 @@ + diff --git a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/SqlSugarClient.cs b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/SqlSugarClient.cs index 7b7693cc3..ded6e27cd 100644 --- a/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/SqlSugarClient.cs +++ b/Src/Asp.NetCore2/SqlSeverTest/SqlSugar/SqlSugarClient.cs @@ -38,7 +38,8 @@ namespace SqlSugar DependencyManagement.TryOracle(); break; case DbType.PostgreSQL: - throw new Exception("开发中"); + DependencyManagement.PostgreSQL(); + break; default: throw new Exception("ConnectionConfig.DbType is null"); }